zhuwt2008
2015-07-03 13:53
采纳率: 0%
浏览 2.5k

C#调用C++的dll中参数出现无法封送处理某字段的问题,请求高手急救!!

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

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

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

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

然后调用

public static class NativeMethod
{
    [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
    public static extern int LoadLibrary(
        [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

    [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
    public static extern IntPtr GetProcAddress(int hModule,
        [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
}

    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 = 100;
        a1.Y = 20;
        A a2 = new A();
        a1.a = a2;
        Console.WriteLine(dofun1(ref a1));
    }

结果报错:“System.TypeLoadException”类型的未经处理的异常在TestDll.exe中发生。其他信息:无法封送处理类型为“TestDll.A”的字段“a”: 该类型不支持封送处理。

这个问题如何解决?请求高手急救,不胜感激!!

2条回答 默认 最新

相关推荐 更多相似问题