2011-03-30 81 views
5

我有一个非托管DLL的函数,它将一个指针作为参数。如何从C#中传递指针而不是'不安全'?如何将C#指针传递给非托管DLL?

下面是一些示例代码:

[DllImport(@"Bird.dll")] 
private static extern bool foo(ushort *comport); 

标题中的相应条目:

BOOL DLLEXPORT foo(WORD *pwComport); 

当我尝试,只是取消对它的引用(&comport),我得到一个错误说:“指针而固定大小的缓冲区只能用于不安全的环境中。

我该如何解决这个问题?

回答

13

使用ref

[DllImport(@"Bird.dll")] 
private static extern bool foo(ref ushort comport); 

调用它像这样:

ushort comport; 
foo(ref comport); 

对于这样的互操作,我宁愿使用UInt16而非ushort为相当于WORD

+0

哦,这很简单! – 2011-03-30 19:09:35

相关问题