我试图学习如何从C#调用非托管代码,但我发现它很难。到目前为止,我已经设法使用基本类型设置了一个简单的场景:
Test.h:
#pragma once
class TestWCM
{
public:
int Hello();
private:
};
Test.cpp的:
#include "Test.h"
int TestWCM::Hello()
{
return 42;
}
然后我创建了一个Visual C ++类库项目:
WCM_Wrapper_Lib.h:
#include "C:\Test.h"
#include "C:\Test.cpp"
using namespace System;
namespace WCM_Wrapper_Lib {
public ref class TestWrapper
{
public:
TestWrapper();
~TestWrapper();
int Hello();
private:
TestWCM* test;
};
}
WCM_Wrapper_Lib.cpp:
#include "stdafx.h"
#include "WCM_Wrapper_Lib.h"
WCM_Wrapper_Lib::TestWrapper::TestWrapper()
{
test = new TestWCM();
}
WCM_Wrapper_Lib::TestWrapper::~TestWrapper()
{
delete test;
}
int
WCM_Wrapper_Lib::TestWrapper::Hello()
{
return test->Hello();
}
最后,我创建了一个Windows窗体应用程序,其中我添加了.dll作为参考。
Form1.cs中:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WCM_Wrapper_Lib;
namespace WCM2_GUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestWrapper testWrapper = new TestWrapper();
MessageBox.Show(testWrapper.Hello().ToString());
}
}
}
现在我的问题是,如果不是int,我将如何修改此代码,我希望Hello()返回一个简单的结构:
struct TestStruct
{
int first;
float second;
};