如何在C#和未管理的C ++库之间传递引用指针?(How to pass a Reference

编程入门 行业动态 更新时间:2024-10-23 19:34:10
如何在C#和未管理的C ++库之间传递引用指针?(How to pass a Reference-to-Pointer between between C# and an un-managed C++ Library?)

在我的C / C ++库中,我有一个这样的原型函数:

long myFunction( const wchar_t*& pszOutput)

Dll为pszOutput分配内存并释放它。

如何从C#调用此函数?

我已经尝试了以下几行的很多变化(使用MarshalAs,......),但是在退出myFunction时我总是遇到崩溃:

[DllImport("mydll.dll", EntryPoint = "myFunction", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern long myFunction(ref string szOutput);

有谁知道,怎么做?

In my C/C++ Library, I've a function with such a prototype:

long myFunction( const wchar_t*& pszOutput)

The Dll allocates the memory for pszOutput and deallocates it too.

How do I call this function from C# ?

I've tried a lot of variation of the following line (with out, with MarshalAs, ...), but I always get a crash when exiting myFunction:

[DllImport("mydll.dll", EntryPoint = "myFunction", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern long myFunction(ref string szOutput);

Does anyone knows, how to do that?

最满意答案

如果你在Windows上,C ++ long不是C# long ,通常是C# int 。 用C ++检查sizeof(long) 。 如果它是4那么它是int 。

尝试传递out IntPtr szOutput ,然后将Marshal.PtrToStringUni()与返回的IntPtr 。

有关类似问题,请参阅例如PInvoke和char ** 。

If you are on Windows, C++ long isn't C# long, it is normally C# int. Check the sizeof(long) in C++. If it is 4 then it is int.

Try passing a out IntPtr szOutput, then use the Marshal.PtrToStringUni() with the returned IntPtr.

See for example PInvoke and char** for a similar problem.

更多推荐

本文发布于:2023-07-25 05:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   如何在   Reference   pass

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!