简体   繁体   English

如何将指针从C#传递给非托管DLL?

[英]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.

相关问题 如何将结构从C#托管结构传递到C ++非托管DLL并得到结果结构? - How can I pass struct from C# managed to C++ unmanaged DLL and get struct in result? 我怎样才能将数组从C#传递到一个非托管DLL中,并以long []形式获取值? - How can I pass an array from C# to an unmanaged DLL as a long [] and get values back? 如何从非托管应用程序将数据传递给C#COM DLL - How to pass data to C# COM DLL from unmanaged application 如何将C ++非托管DLL转换为C# - How can I convert C++ unmanaged DLL to C# 如何防止他人在C#应用程序中使用我的非托管DLL? - How can I prevent others from using my unmanaged DLL in their C# application? 无法将C#int传递给非托管C ++ DLL - can't pass C# int to unmanaged C++ DLL 如何使用非托管导出从C ++发送函数指针到C#dll以用作回调 - How to send a function pointer using Unmanaged Exports from C++ to C# dll to be used as callback 如何使用指针调用非托管dll填充C#中的结构 - How to call unmanaged dll to populate struct in C# using a pointer 在C#中,如何调用返回包含字符串指针的非托管结构的DLL函数? - In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer? 如何从 C# 的 char * 传递和接收数据到非托管 C++ DLL - How to pass and receive data from a char * from C# to an unmanaged C++ DLL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM