ITPub博客

首页 > > > c#调用c++dll函数时参数传递的问题?怎样正确传值?

c#调用c++dll函数时参数传递的问题?怎样正确传值?

作者:dapan 时间:2019-09-20 10:37:06 0 删除 编辑

在c++项目cpptest.dll中定义: struct A {     int X;     int Y; };

extern "C" __declspec(dllexport) int fun1(A *a);

int fun1(A *a) {     return a->X; }

在C#项目中定义: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]     class A     {         public int X;         public int Y;     }

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int dofun(ref A a1);   

class Program
{
    static void Main(string[] args)
    {
        //1. 动态加载C++ Dll
        int hModule = NativeMethod.LoadLibrary("cpptest.dll");
        if (hModule == 0) return;
        //2. 读取函数指针
        IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "fun1");
        //3. 将函数指针封装成委托
        dofun dofun1 = (dofun)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(dofun));

        A a1 = new A();
        a1.X = 1;
        a1.Y = 2;
        Console.WriteLine(dofun1(ref a1));
    }
}

为什么每次运行输出都不相同,且数字不是1也不是2,而是类似7825552,14052168,21507032?该如何修改呢?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/758/viewspace-3168146/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-08-07

  • 博文量
    4504
  • 访问量
    87094