我开始为这个问题而苦恼。我已经搜索并寻求帮助,但我尝试过的一切似乎都不起作用。我显然做错了什么。
无论如何 - 我有一个 C# 结构定义为:
public struct TestStruct
[StructLayout(LayoutKind.Sequential)]
{
public int num;
public IntPtr intArrayPtr;
}
在我的 C# 代码的主体中,我有:
public class Testing
{
[DllImport("testing.dll")]
static extern void Dll_TestArray(out IntPtr intArrayPtr);
public GetArray()
{
IntPtr structPtr = IntPtr.Zero;
TestStruct testStruct;
structPtr = Marshal.AllocHGlobal(Marshal.SizeOf(testStruct));
Marshal.StructureToPtr(testStruct, structPtr, false);
Dll_TestArray(structPtr);
testStruct = (TestStruct) Marshal.PtrToStructure(structPtr, typeof(TestStruct));
}
}
现在是 C++ 部分。从结构开始:
struct TestStruct
{
public:
int num;
int* intArray;
}
现在是函数:
extern "C" __declspec(dllexport) void Dll_TestArray(TestStruct *&testStruct)
{
int num = 15;
testStruct->num = num;
testStruct->intArray = new int[num];
for (int i = 0; i < num; i++)
testStruct->intArray[i] = i+1;
}
所以 - 我遇到的问题是,当我将结构返回到 C# 时,我的结构不是它应该的样子。我可以看到 num 字段已正确填写:它显示 15。但是,IntPtr 仍设置为零。在 c++ 中完成的数组创建尚未执行到 c#。
如果我尝试退后一步,回到 dll 函数,我可以看到数组创建正常并且仍然保留信息。
因此结构中的 c# intptr 没有被设置为在 c++ 中创建的指针(如果这有意义的话)。
所以我的问题实际上是 - 如何使它正常工作?
我希望能够从 dll 中恢复,这是一个包含我需要的所有信息的结构。也就是说,在这个例子中,元素的数量,以及指向数组的指针。这样,我就可以在 intptr 上执行 Marshal.Copy 以获取数组。
如果有其他方法可以做到这一点,我非常乐意这样做。我已经尝试了几种方法,但无济于事。这包括在 c# 中尝试以下结构(其中包含 int 数组,而不是 intptr):
public struct TestStruct
{
public int num;
// i have tried various methods to marshal this- eg:
// [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_I4]
public int[] intArray;
}
而且我还尝试通过引用本身而不是 intptr 来传递结构。 对此事的任何帮助将不胜感激。我无法更改 C++ 代码,但可以更改 C# 代码。
最佳答案
首先将 C++ 代码更改为仅使用一个间接级别:
extern "C" __declspec(dllexport) void Dll_TestArray(TestStruct &testStruct)
{
const int num = 15;
testStruct.num = num;
testStruct.intArray = new int[num];
for (int i=0; i<num; i++)
testStruct.intArray[i] = i+1;
}
在 C# 方面,您需要这样:
public struct TestStruct
{
public int num;
public IntPtr intArray;
}
[DllImport("testing.dll", CallingConvention=CallingConvention.Cdecl)]
static extern void Dll_TestArray(out TestStruct testStruct);
public GetArray()
{
TestStruct testStruct;
Dll_TestArray(out testStruct);
int[] arr = new int[testStruct.num];
Marshal.Copy(testStruct.intArray, arr, 0, arr.Length);
// need to call back to DLL to ask it to deallocate testStruct.intArray
}
您还需要导出一个函数,该函数将释放您使用 C++ 堆分配的数组。否则你会泄露它。
也许更简单的方法是更改设计,让调用者分配缓冲区。
关于c# - 将包含未知大小的 int 数组的结构从 c# 传递到 c 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17084272/