我有以下问题:
我有一个从非托管 C++ dll 调用函数的 C# 应用程序。dll 中有一个初始化函数,它在 C# 和 C++(基本上是值及其类型的列表)之间创建一个接口,该接口将存储在一个结构中。
之后,有一个 C# 应用程序发送给 dll 的回调函数,dll 每隔一段时间就会调用一次,并返回接口中定义的结构变量(或字节数组)。
我的问题:你将如何传递和编组这个结构?是否可以传递结构本身,或者我应该传递一个字节数组?
如果您传递一个字节数组,当返回到 C# 应用程序时您将如何编组它?
我现在拥有的:
在 C# 应用程序中:
编组回调函数:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void ProcessOutputDelegate(???); // not sure what should be here.
导入dll函数:
[DllImport("MyDLL.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern void Test(ProcessOutputDelegate ProcessOutput);
调用dll函数:
ProcessOutputDelegate process = new ProcessOutputDelegate(ProcessOutput);
new thread(delegate() { Test(process); } ).Start();
处理输出:
public void ProcessOutput(???)
{
// Assume we have a list of values that describes the struct/bytes array.
}
在 C++ dll 中,我有以下结构(这是一个示例,因为可以在不同的运行时调用不同的 dll):
struct
{
int x;
double y;
double z;
} typedef Interface;
以及 C# 应用程序调用的函数:
__declspec(dllexport) void Test(void (*ProcessOutput)(Interface* output))
{
int i;
Interface* output = (Interface*)malloc(sizeof(Interface));
for (i = 0; i < 100; i++)
{
sleep(100);
output->x = i;
output->y = i / 2;
output->z = i / 3;
ProcessOutput(output); // or generate a bytes array out of the struct
}
}
编辑:
C# 应用程序是一个通用 GUI,假设显示由某些 c++ dll 执行的一些繁重的计算。在初始化过程中,dll 告诉 GUI 应该呈现的变量(及其类型),并根据这些方向构建 GUI(同样,计算和变量可能会改变,值可能是 ints、float、字符...)。之后,dll 运行并在每几个时间步中调用回调函数来更新 GUI。这应该适用于任何实现这个想法的dll:生成一个接口,然后根据这个接口发送信息。