我是C#和封送的新手。我需要在C#中使用我的C函数,但是我从C func返回的值不正确(或者我不知道如何将它转换为正确的答案)。DllImport和char Marshaling
c来源:
#include "main.h"
char *Ololo(char *arg, int &n3)
{
char *szRet;
szRet=(char*)malloc(strlen(arg)+1);
strcpy(szRet,arg);
n3 = strlen(szRet);
return szRet;
}
C头:
extern "C" __declspec(dllexport) char *Ololo(char *arg, int &n3);
C#源: “伯仲”
class Program
{
[DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr Ololo([In] char[] arg, ref Int32 n3);
static void Main(string[] args)
{
string n1 = "ololo";
char[] chars = new char[n1.Length];
chars = n1.ToCharArray();
Int32 n3 = 0;
IntPtr result;
result = Ololo(chars, ref n3);
string n4 = Marshal.PtrToStringUni(result,n3);
Console.WriteLine(n4);
}
}
我已经得到了一些回报,像
对不起,我英文不好
----------------------解决--------------- --------
class Program
{
[DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr Ololo([MarshalAs(UnmanagedType.LPStr)]string arg, ref Int32 n3);
static void Main(string[] args)
{
string n1 = "ololo";
Int32 n3 = 0;
int n2 = n1.Length;
IntPtr result;
result = Ololo(n1, ref n3);
string n4 = Marshal.PtrToStringAnsi(result, n3);
Console.WriteLine(n4);
}
}
工作正常。在n3中,我得到了5和n4奥洛洛!感谢您的快速解答!
btw'int&n3'不是C,它的C++表示法。 –
你还没有解决任何问题,代码泄漏了字符串的内存。 –
可能重复的[Char *编组在C#](http://stackoverflow.com/questions/1808581/char-marshalling-in-c-sharp) –