C#调用C++的方法

来源:互联网 发布:华东师大公共数据 编辑:程序博客网 时间:2024/05/19 09:10
    网上有很多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);    }
0 0