概括:
我有一堆必须从 C# 调用的 C 函数。我目前的工作解决方案基于函数重载,我想知道是否有更优雅的解决方案。
C的东西:
头文件中的某处
typedef struct _unknown_stuff * handle; // a opaque pointer
函数示例
func( uint num_entries,
handle * objects,
uint * n)
{ ... }
在 C 中,该函数的使用应与此类似:
// warning: i bet that the syntax is not correct but you should get the idea...
uint n;
func(0, null, &n);
handle * objects = malloc(n * sizeof(handle));
func(n, objects, null);
C# 的东西:
现在我在 C# 中执行以下操作:
public struct handle
{
public IntPtr Pointer;
}
// version to get number of objects
[DllImport(dll, ...]
private static extern void
func( uint must_be_zero,
object must_be_null,
out uint n);
// version to get the actual data
[DllImport(dll, ...]
private static extern void
func( uint num_entries,
[Out] handle[] objects,
int must_be_zero);
接着:
handle[] objects;
uint n = 42;
func(0, null, out n);
objects = new handle[n];
func(n, objects, 0);
问题
由于我是 C# 菜鸟,我想知道这是否是最好的方法。特别是我想知道是否有办法重载函数。