我已经写这段代码的正常工作:
C++代码传递一个字符串数组从C++到C#
extern "C"
{
const MYLIBRARY_EXPORT char* giefStrPlx(char* addon)
{
return addon;
}
}
C#代码
[DllImport("ClassLibrary1")]
private static extern IntPtr giefStrPlx(string x);
void Start()
{
IntPtr stringPtr = giefStrPlx("Huntsman");
string huntsman = Marshal.PtrToStringAnsi(echoedStringPtr);
}
后这huntsman
包含“亨斯迈”。
我的问题是对字符串数组做类似的操作。我写了下面的功能
extern "C"
{
const MYLIBRARY_EXPORT bool fillStrArray(char** lizt, int* length)
{
char* one = "one";
char* two = "two";
char* three = "three";
lizt[0] = one;
lizt[1] = two;
lizt[2] = three;
*length = 3;
}
}
然后我试着写了下面这段代码在C#
[DllImport("ClassLibrary1")]
private static extern bool fillStrArray(ref IntPtr array, ref int length);
void Start()
{
IntPtr charArray = IntPtr.Zero;
int charArraySize = 0;
fillStrArray(ref charArray, ref charArraySize);
IntPtr[] results = new IntPtr[charArraySize];
Marshal.Copy(charArray, results, 0, charArraySize);
foreach (IntPtr ptr in results)
{
string str = Marshal.PtrToStringAnsi(ptr);
}
}
不工作。所以现在我对如何完成这一点有点失落。
你的C代码要求你传递一个指向内存的指针,它可以写入字符串指针。 IntPtr.Zero不可写。你也不知道你需要分配多少内存。使用IntPtr charArray = Marshal.AllocHGlobal(crossMyFingers)其中crossMyFingers是一个很大的数字,对于此代码至少需要3 * IntPtr.Size,但应该较大以减少堆损坏的几率。你可以设置* length *参数来帮助它避免这种腐败。 –
感谢您的指针。即使改变,我仍然有问题。我试图在Unity中使用它,并且插件崩溃,这使得调试更加困难。 而不是将指针传递给数组我只是返回一个指针,与第一个示例中的不同。 – Bjorninn