[英]How can I pass a pointer from C# to an unmanaged DLL?
I have an unmanaged DLL with a function that takes a pointer as an argument. 我有一个非托管DLL,其函数将指针作为参数。 How do I pass a pointer from C# without being 'unsafe'? 如何从C#传递指针而不是“不安全”?
Here's some example code: 这是一些示例代码:
[DllImport(@"Bird.dll")]
private static extern bool foo(ushort *comport);
The corresponding entry in the header: 标题中的相应条目:
BOOL DLLEXPORT foo(WORD *pwComport);
When I try and simply dereference it ( &comport
), I get an error saying: " Pointers and fixed size buffers may only be used in an unsafe context. " 当我尝试简单地取消引用它( &comport
)时,我得到一个错误说:“ 指针和固定大小的缓冲区只能在不安全的上下文中使用。 ”
How do I work around this? 我该如何解决这个问题?
Use ref
: 使用ref
:
[DllImport(@"Bird.dll")]
private static extern bool foo(ref ushort comport);
Call it like so: 这样称呼它:
ushort comport;
foo(ref comport);
For interop like this, I'd prefer to use UInt16
rather than ushort
as the equivalent to WORD
. 对于像这样的互操作,我更喜欢使用UInt16
而不是ushort
作为WORD
的等价物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.