【发布时间】:2021-01-29 01:04:17
【问题描述】:
我正在尝试将一个双精度数组传递给从 C++ DLL 导入到 C# 的函数。 该函数在 C++ DLL 中如下所示(使用调用约定 cdecl):
__declspec(dllexport) void FunctionToImport(void* values, size_t numberOfValues, const char* someString);
这里是 C# 中的导入:
[DllImport("DLLToImport.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void FunctionToImport(IntPtr values, int numberOfValues, string someString);
以这种方式从 C# 调用时:
double[] bytes = { 1.0, 2.0, 3.0, 4.0 };
IntPtr testvalues = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, testvalues, bytes.Length);
CSharpClass.FunctionToImport(testvalues, Marshal.SizeOf(testvalues), "someString";
Marshal.FreeHGlobal(testvalues);
我收到 AccessViolationException,有时程序会崩溃。
将一个 size_t 模拟量的数组传递给库的正确方法是什么?
【问题讨论】:
-
第一个参数是 IntPtr[]。数组元素应该指向什么(如果有的话)是完全不明显的。展示一些示例 C/C++ 代码,这些代码使用此函数来获得您需要的帮助。
标签: c# c++ pinvoke marshalling dllimport