C# DLL 互操作:本机函数接收的参数值与从 C# 调用的参数值不同
我有一个问题,我正在通过 C 接口进行一些 C#<->C++ 互操作,并且我有一个从这样的 dll 导入的函数,
[DllImport("pixi_api", EntryPoint = "pixi_sprite_asm_file", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PixiStringMarshaler))]
private static extern pixi_string _pixi_sprite_asm_file(IntPtr sprite);
并且它被调用,例如,像这样
var cstr = _pixi_sprite_asm_file(data_pointer);
DLL 中的实际函数看起来像这样,
EXPORT pixi_string pixi_sprite_asm_file(pixi_sprite_t pixi_sprite_ptr) {
const char* const ptr = pixi_sprite_ptr->asm_file;
pixi_string str = {ptr, static_cast<int>(strlen(ptr))};
return str;
}
但有一个问题: 如果我在调用 _pixi_sprite_asm_file 之前打印从 C# 代码传递的 data_pointer,然后在 c 本机函数调用(pixi_sprite_ptr)内打印它,我会得到 2 个完全不同的指针,因此,一切都会爆炸。
例如:
数据指针=> 191BF4A0300
pixi_sprite_ptr => 0x00007ffc0e1ebb92
我还有其他返回简单编组类型(例如整数)的方法,这些方法不存在此问题,并且指针不变地传递。 例如,这个有效,指针是相同的并且它返回预期值:
[DllImport("pixi_api", EntryPoint = "pixi_sprite_line", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I4)]
private static extern int _pixi_sprite_line(IntPtr sprite);
我不知道可能出了什么问题。
I have a problem, I'm doing some C#<->C++ interop via a C interface and I have a function that I import from a dll like this
[DllImport("pixi_api", EntryPoint = "pixi_sprite_asm_file", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PixiStringMarshaler))]
private static extern pixi_string _pixi_sprite_asm_file(IntPtr sprite);
and it gets called, for example, like this
var cstr = _pixi_sprite_asm_file(data_pointer);
the actual function in the DLL looks like this
EXPORT pixi_string pixi_sprite_asm_file(pixi_sprite_t pixi_sprite_ptr) {
const char* const ptr = pixi_sprite_ptr->asm_file;
pixi_string str = {ptr, static_cast<int>(strlen(ptr))};
return str;
}
however there's a problem:
if I print the data_pointer passed from the C# code, before the call to _pixi_sprite_asm_file and then I print it while inside the c native function call (the pixi_sprite_ptr), I get 2 completely different pointers and as such, everything explodes.
e.g:
data_pointer => 191BF4A0300
pixi_sprite_ptr => 0x00007ffc0e1ebb92
I have other methods that return simple-to-marshal types such as ints, that don't have this problem and the pointer gets passed unchanged.
e.g this one works, the pointers are the same and it returns the expected value:
[DllImport("pixi_api", EntryPoint = "pixi_sprite_line", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I4)]
private static extern int _pixi_sprite_line(IntPtr sprite);
I have no clue what could be going wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论