【发布时间】:2011-07-11 14:34:40
【问题描述】:
我将 byte[] 传递给接受 unsigned char* 的函数
我可以做到这一点的一种方法是传递一个 IntPtr,并在托管代码中分配/取消分配内存,如下所示:
-
在 C++ DLL 中
extern "C" { __declspec(dllexport) void __stdcall Foo(int length, unsigned char** message); } -
在 C# 中
[DllImport(@"MyDll.dll"] public static extern void Foo(int length, ref IntPtr msg); byte[] msg = new byte[] {0,1,2,3}; IntPtr ip = Marshal.AllocHGlobal(msg.Length); Marshal.Copy(msg, 0, ip, msg.Length); UnmanagedCode.Foo(msg.Length, ref ip); Marshal.FreeHGlobal(ip);
我也可以这样做:
-
在 C++ DLL 中
extern "C" { __declspec(dllexport) void __stdcall Foo(int length, unsigned char* message); } -
在 C# 中
[DllImport(@"MyDll.dll"] public static extern void Foo(int length, byte[] msg); byte[] msg = new byte[] {0,1,2,3}; UnmanagedCode.Foo(msg.Length, msg);
两种实现都运行良好,但在我的第二个示例中,内存(对于 unsigned char* 消息)是如何管理的。我猜内存是在调用 Foo 时分配的,并在它返回时释放(所以它的行为很像第一个示例) - 这是正确的吗?
谢谢
【问题讨论】:
-
我不明白为什么你会在第一个例子中传递
ref ip。您不可能更改ip的值。在第二个示例中,unsigned char message[]的读取效果要好得多。最后,如果您要传递 IP 地址,结构体将是可行的方法——不需要长度参数。
标签: c# arrays memory-management pinvoke dllimport