获取从本机 dll 到 C# 应用程序的结构数组
我有一个 C# .NET 2.0 CF 项目,需要在本机 C++ DLL 中调用方法。此本机方法返回 TableEntry
类型的数组。当调用本机方法时,我不知道数组有多大。
如何将表从本机 DLL 获取到 C# 项目?下面是我现在所拥有的。
// in C# .NET 2.0 CF project
[StructLayout(LayoutKind.Sequential)]
public struct TableEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string description;
public int item;
public int another_item;
public IntPtr some_data;
}
[DllImport("MyDll.dll",
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Auto)]
public static extern bool GetTable(ref TableEntry[] table);
SomeFunction()
{
TableEntry[] table = null;
bool success = GetTable( ref table );
// at this point, the table is empty
}
// In Native C++ DLL
std::vector< TABLE_ENTRY > global_dll_table;
extern "C" __declspec(dllexport) bool GetTable( TABLE_ENTRY* table )
{
table = &global_dll_table.front();
return true;
}
谢谢, 保罗·H
I have a C# .NET 2.0 CF project where I need to invoke a method in a native C++ DLL. This native method returns an array of type TableEntry
. At the time the native method is called, I do not know how large the array will be.
How can I get the table from the native DLL to the C# project? Below is effectively what I have now.
// in C# .NET 2.0 CF project
[StructLayout(LayoutKind.Sequential)]
public struct TableEntry
{
[MarshalAs(UnmanagedType.LPWStr)] public string description;
public int item;
public int another_item;
public IntPtr some_data;
}
[DllImport("MyDll.dll",
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Auto)]
public static extern bool GetTable(ref TableEntry[] table);
SomeFunction()
{
TableEntry[] table = null;
bool success = GetTable( ref table );
// at this point, the table is empty
}
// In Native C++ DLL
std::vector< TABLE_ENTRY > global_dll_table;
extern "C" __declspec(dllexport) bool GetTable( TABLE_ENTRY* table )
{
table = &global_dll_table.front();
return true;
}
Thanks,
PaulH
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当将未知大小的数组从本机编组到托管时,我发现最好的策略如下:
IntPtr
编组到托管端的自定义结构。因此,我将对您的代码进行以下更改。
本机:
托管:
When marshalling an array of unknown size from native to managed I find the best strategy is as follows
IntPtr
in managed codeIntPtr
to the custom struct on the managed side.As such I would make the following changes to your code.
Native:
Managed: