2 zhuwt2008 zhuwt2008 于 2015.07.04 00:23 提问

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

在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?该如何修改呢?

1个回答

zhuwt2008
zhuwt2008   2015.07.04 09:34
已采纳

class A换成struct A

Csdn user default icon
上传中...
上传图片
插入图片