DllImport,Char *&和StringBuilder C/C# [英] DllImport, Char*& and StringBuilder C/C#

查看:156
本文介绍了DllImport,Char *&和StringBuilder C/C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我试图查看几乎所有的海报解决方案,但未能找到合适的解决方案.

I have a problem, I tried to look at almost all the poster solutions, unsuccessful to find a suitable one.

问题很简单,要在托管C#中获得非托管C代码的返回字符串.c函数是:

The question is easy, Want to have a return string from unmanaged C code in my managed C#. The c function is:

extern "C" __declspec(dllexport) int process_batch (char *&result);

在C#中,我导入了DLL:

and in C# I imported the DLL:

[DllImport("mydll.dll")]
public static extern IntPtr process_batch(StringBuilder result);

我运行了,但是我的StringBuilder中的返回值是一个7-8的无意义的字符串!(我认为是内存地址)

I run, but the return value in my StringBuilder is a 7-8 character string of non-sense! (I think the memory address)

我尝试在StringBuilder之前添加ref,这一次我在StringBuilder中获得了正确的返回值,但我得到了AccessViolationException:尝试读取或写入受保护的内存.这通常表明其他内存已损坏.

I tried adding ref before the StringBuilder, this time I get the correct return value in StringBuilder but I get AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

所以我需要您的帮助来解决此问题.

So I need your help to fix this.

还有一件事,我在c中使用malloc将内存分配给char *变量.

Just one more thing, I use malloc in c for allocating the memory to the char* variable.

谢谢

推荐答案

如果您确实要这样做,请将参数作为 ref IntPtr 传递,然后调用

If you really want to do that, pass the parameter as a ref IntPtr, then call Marshal.PtrToStringAnsi, or similar.

[DllImport("mydll.dll")]
public static extern IntPtr process_batch(ref IntPtr result);

请注意,由于要在C中使用 malloc 分配字符串,.NET程序必须跟踪返回的指针,以便可以将其传递回给您进行释放..否则会发生内存泄漏.

Note that, since you're allocating the string with malloc in C, the .NET program will have to keep track of the returned pointer so that it can pass it back to you to be deallocated. Otherwise you'll have a memory leak.

如果要传递 ref StringBuilder ,则将无法取消分配C程序分配的内存.

If you were to pass a ref StringBuilder, you wouldn't be able to deallocate the memory that was allocated by the C program.

另外,正如某人在另一篇文章中评论的那样,您需要设置调用约定:

Also, as somebody commented in another post, you need to set the calling convention:

[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]

这篇关于DllImport,Char *&和StringBuilder C/C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆