我是 C# 和编组的新手。我需要在 C# 中使用我的 C func,但我的 C func 返回值不正确(或者我不知道如何将其转换为正确答案)。
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);
}
}
我有返回类似“o???”的东西
对不起英语不好
- - - - - - - - - - - 解决了 - - - - - - - - - - - -
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 ololo!感谢您的快速回答!