【发布时间】:2017-11-27 23:32:24
【问题描述】:
我有一个 DLL pin C++,它接受两个参数,类似于 C 中的 main() 函数:参数数量,后跟指向各个参数的指针数组:
__declspec(dllexport) void Calculate(int argc, void** argv)
{
if (argc >= 7)
{
auto sourceX = *((int*)(argv[0]));
auto sourceY = *((int*)(argv[1]));
auto iterations = *((int*)(argv[2]));
auto resize = *((bool*)(argv[3]));
auto input = (double*)(argv[4]);
auto targetX = *((int*)(argv[5]));
auto targetY = *((int*)(argv[6]));
// Do computations
}
}
我能够以这种方式从另一个 C 代码调用导出的函数(在通过 LoadLibrary 和 GetProcAddress 调用加载 DLL 库之后):
int X, Y, iterations;
bool Resize;
double* Input;
// Initialize variables, allocate data for Input
// ...
void* Params[] = { &X, &Y, &iterations, &Resize, Input, &X, &Y };
_Calculate(7, Params);
但是,当我尝试从 C# 调用 DLL 时,它崩溃了。这是我正在使用的 C# sn-p:
[DllImport("computedll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern void Calculate(int argc, void** argv);
public void Compute()
{
int X, Y, iterations;
bool Resize;
double* Input;
// Initialize variables, allocate data for Input
// ...
var Parameters = stackalloc void*[7];
Parameters[0] = &X;
Parameters[1] = &Y;
Parameters[2] = &iterations;
Parameters[3] = &Resize;
Parameters[4] = Input;
Parameters[5] = &X;
Parameters[6] = &Y;
Calculate(7, Parameters);
}
我在这里做错了什么?有没有办法使这种使用指针数组(void**)的模式起作用?提前致谢。
【问题讨论】:
-
猜测您已经验证了您的 C++ 代码并且您的 C# 代码使用相同的指针大小?