Windows Mobile 平台上的 PInvoke
所以我试图调用非托管 C++ dll 中的函数。
void foo(char* in_file, char * out_file)
在我的 C# 应用程序中,我声明了与
[DllImport("dll.dll")]
public static extern void foo(byte[] in_file, byte[] out_file);
实际参数相同的函数,我通过 ASCII 编码器传递,就像这样
byte[] param1 = Encoding.ASCII.GetBytes(filename1);
byte[] param2 = Encoding.ASCII.GetBytes(filename2);
foo(param1, param2);
一切正常,除了 param1 的长度为 0 或 36 或 72 个字符(字节)时。然后由于某种原因,DLL 报告接收到的长度 1、38、73,并在最后附加了 0x16 字符。
我浪费了半天时间尝试调试并理解为什么会发生这种情况。有什么想法吗? 36的倍数有什么意义?
编辑/解决方案:
在我发布此内容后,我突然想到了一个可能的答案。通过在将字符串转换为字节数组之前将空字符 0x0 附加到字符串末尾,我已经消除了这个问题。虽然我不确定这是否是设计使然。
So I'm trying to invoke a function I have in my unmanaged C++ dll.
void foo(char* in_file, char * out_file)
In my C# application I declare the same function as
[DllImport("dll.dll")]
public static extern void foo(byte[] in_file, byte[] out_file);
The actual parameters I pass through an ASCII encoder like so
byte[] param1 = Encoding.ASCII.GetBytes(filename1);
byte[] param2 = Encoding.ASCII.GetBytes(filename2);
foo(param1, param2);
Everything works, except when the length of param1 is 0 or 36 or 72 characters (bytes). Then for some reason the DLL reports the received length of 1, 38, 73 with the 0x16 character appened on the very end.
I have wasted half a day trying to debug and understand why this is happening. Any ideas?
What is the significance of multiples of 36?
Edit/Solution:
After I posted this a possible answer struck me. By appending the null character 0x0 to the end of my strings before converting them to byte arrays I have eliminated the problem. Although I'm not sure if that is by design.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您自己偶然发现了答案 - 没有传递给函数的长度。
您需要仔细考虑您在哪些函数上运行这些函数以及 ASCII 是否真的是您想要的。
您可能真的想要这样,不需要 ASCII 编码,并且在编组类型中显式显示空终止:
但是请检查您的 foo() 实现并确保您了解您真正期望传入的内容。
You've stumbled across the answer yourself - nowhere is the length passed to the function.
You need to think carefully about what functions you are running these on and whether ASCII is really what you want.
You probably really want this, with no ASCII encoding necessary and null termination explicit in the marshaled type:
But check your foo() implementation and make sure you understand what you really expect to be passed in.