在C#中使用本机DLL

时间:2012-02-23 19:57:20

标签: .net c dll native dllimport

我们聘请了一名C程序员来开发一个用于.NET应用程序的本机组件。我们就概念API达成了一致意见。我将传递他的方法两个数组,他将返回一个数组。我今天得到了代码。这是头文件。真实姓名模糊不清:

__declspec(dllexport) int NativeMethod(
    struct params * config,
    int c_input_a_rows, 
    struct input_a_row *input_a_rows,
    int c_input_b_rows, 
    struct input_b_row *input_b_rows,
    int c_count, 
    int *p_c_output_rows, 
    struct output_row * output_rows);

struct params
{
    int a;
    int b;
    int c;
    double d;
    double e;
    int f;
    int g;
    char h[1000];
};

struct input_a_row
{
    int a;
    int b;
    double c;
};

struct input_b_row
{
    int a;
    int b;
    int c;
    int d;
    int e;
    double f;
    double g;
};

struct output_row
{
    int a;
    int b;
    int c;
    int d;
    int e;
    int f;
    int g;
    double h;
    double i;
    double j;
};

由此我使用P/Invoke Interop Assistant生成.NET代码。打开DLL,我无法让它工作。它抱怨该文件没有程序集清单。所以我将头文件插入到SigImpl Translate Snipped中并得到了这个:

[DllImport("the.dll", EntryPoint="NativeMethod")]
public static extern int NativeMethod(
    ref params config,
    int c_input_a_rows, 
    ref input_a_row input_a_rows,
    int c_input_b_rows, 
    ref input_b_row input_b_rows,
    int c_count, 
    ref int p_c_output_rows, 
    ref output_row output_rows);

它还按预期创建所有结构。每个人都有一个class属性:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]

两个问题。这段代码是否正确生成?其次,我该如何使用它?签名没有数组。我知道我可能需要以某种方式使用指针,但是如何?我不希望你为我解决这个问题,但是你可以指点我一些方法来理解如何在没有学习低本地编程课程的情况下解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

好的,在我发布这个问题后,我又开始乱砍了。我试过的第一件事就是工作!

    private static extern int NativeMethod(
        params config,
        input_a_row[] input_a_rows,
        input_b_row[] input_b_rows,
        int count,
        ref output_row[] output_rows);

我还有另一件事要做。我收到一个错误,没有找到入口点。我通过使用DUMPBIN(来自VS控制台)解决了这个问题,发现导出实际上名为?NativeMethod@@YAHPAUconfig@@HPAUinput_row_a@@HPAUinput_row_b@@HPAHPAUoutput_row@@@Z。这有多脆弱?!