从 C++ 非托管 dll 传递 C# 函数
Posted
技术标签:
【中文标题】从 C++ 非托管 dll 传递 C# 函数【英文标题】:Passing C# function from C++ unmanaged dll 【发布时间】:2014-01-20 15:30:28 【问题描述】:我有带有 C++ DLL 接口的设备,我应该创建 C# 类来控制它。我没有(断开)连接到此设备的问题,但我无法获得读取功能:
接口函数定义为:
bool Driver_Read(int DeviceNo, unsigned char *pReadBuf, unsigned long ReadLen, unsigned long *pReadLen)
我做了一些研究,发现这段代码应该可以工作:
[DllImport("..\\..\\..\\..\\Driver.dll")]
public static extern bool Driver_Read(int deviceNo, StringBuilder pReadBuf, ulong readLen, ref UInt32 pReadLen);
但是当我运行它时,我得到一个 AccessViolationException :“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”
很多人都有类似的问题,但对我没有任何帮助。 你知道,问题可能出在哪里吗?提前致谢。
【问题讨论】:
看起来需要pReadLen
才能确定字符串的长度。您不能像那样直接进行StringBuilder
转换。
那我应该改用什么?
我不知道,我知道足够多的 PInvoke 知道出了什么问题,但还不足以修复它。
看看这个:***.com/questions/13991060/…
当我使用 IntPtr 而不是 StringBuilder 时,它说它与非托管目标签名不匹配。
【参考方案1】:
试试这个:
[DllImport("..\\..\\..\\..\\Driver.dll")]
public static extern bool Driver_Read(int DeviceNo, IntPtr pReadBuf, uint ReadLen, ref uint pReadLen)
这应该有助于将类型从 C++ 转换为 C#:http://msdn.microsoft.com/en-us/library/ac7ay120(v=vs.110).aspx
【讨论】:
以上是关于从 C++ 非托管 dll 传递 C# 函数的主要内容,如果未能解决你的问题,请参考以下文章