从C#调用C ++函数 [英] Calling C++ function from C#
本文介绍了从C#调用C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下C ++函数
void FillAndReturnString(char ** someString)
{
char sourceString[] = "test";
*someString = new char[5];
memcpy(*someString, sourceString, 5);
}
它被声明为
extern "C"
{
__declspec(dllexport) void __cdecl FillAndReturnString(char ** someString);
}
如何从C#调用此函数?
How do I call this function from C#?
感谢
推荐答案
您需要知道您在c ++函数中分配非托管内存块,因此不可能从C#代码中传递受管字符串或数组对象以保持char数组。
You need to know that you're allocating unmanaged memory block in your c++ function, so it will not be possible to pass a managed String or Array object from C# code to 'hold' the char array.
一种方法是在您的本地dll中定义删除函数,并调用它来释放内存。在受管理方面,您可以暂时使用 IntPtr 结构持有指向c ++ char数组的指针。
One approach is to define 'Delete' function in your native dll and call it to deallocate the memory. On the managed side, you can use IntPtr structure to temporarily hold a pointer to c++ char array.
// c++ function (modified)
void __cdecl FillAndReturnString(char ** someString)
{
*someString = new char[5];
strcpy_s(*someString, "test", 5); // use safe strcpy
}
void __cdecl DeleteString(char* someString)
{
delete[] someString
}
// c# class
using System;
using System.Runtime.InteropServices;
namespace Example
{
public static class PInvoke
{
[DllImport("YourDllName.dll")]
static extern public void FillAndReturnString(ref IntPtr ptr);
[DllImport("YourDllName.dll")]
static extern public void DeleteString(IntPtr ptr);
}
class Program
{
static void Main(string[] args)
{
IntPtr ptr = IntPtr.Zero;
PInvoke.FillAndReturnString(ref ptr);
String s = Marshal.PtrToStringAnsi(ptr);
Console.WriteLine(s);
PInvoke.Delete(ptr);
}
}
}
这篇关于从C#调用C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文