您的位置:首页 > 编程语言 > C语言/C++

C#调用C++的方法

2016-01-06 15:12 369 查看
网上有很多C#调用C++的帖子,我之前走了不少弯路,现总结出来希望大家少走一些弯路,如果有什么不对的地方,欢迎大家随时纠正~
1.建立一个project,令其输出格式为dll。
2. 对于每一个被dll 封装的函数,要写成如下格式,之后build,即可生成dll。


typedef struct _testStru
{
float x;
float y;
float z;
}testStru;

extern "C" __declspec(dllexport) testStru* testReturnStruct(){
testStru *stru = new testStru();
stru->x = 1.1;
stru->y = 1.2;
stru->z = 1.3;
return stru;
}


3.再新建一个project,调用刚刚生成了dll。定义一个nativemethod class,如下


class NativeMethod
{
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct TestStru
{
public Single x;
public Single y;
public Single z;
};
[DllImport("NativeLibrary.dll", EntryPoint = "testReturnStruct")]
public static extern IntPtr testReturnStruct();

[DllImport("NativeLibrary.dll", EntryPoint = "testOutStruct")]
public static extern void testOutStruct(ref TestStru p);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: