如何使用非托管C/ c++结构体和函数

How to use unmanaged C/C++ structs and functions

本文关键字:c++ 结构体 函数 何使用      更新时间:2023-10-16

我的任务是找出一种方法(如果可能的话)将用C/c++(更多的C而不是c++)编写的商业程序的低级处理部分转换为托管库,以便与c#更新的程序一起使用。我有完整的源代码在Visual c++ 6.0随着DLL的和静态库。

一个必须的要求是不修改任何C/c++代码——只是在它周围创建一个包装器。我相信我会尝试创建一个托管的c++ DLL。在许多函数中都广泛使用结构体和结构体指针。

考虑C/c++头文件中的类似内容:

typedef struct {
   union {
       char *char_p;
       void *void_p;
   }
   int a;
   void *rsvd[16];
 } sample_struct;
int sample_func(sample_struct *struct_p, double x);
int sample_func(sample_struct *struct_p, double x, double y);

如何将其包装到CLR包装器中?

非常感谢任何反馈。我甚至愿意接受不同的方法。

谢谢。

你可以先创建一个包装器重构:因为托管c++没有联合,所以使用cp_valid作为标志(cp或vp是有效的)。

ref struct wrapper_st {
    String^ cp;
    IntPtr^ vp;
    bool cp_valid;
    int a;
    array<IntPtr^>^ rsvd;
};
第二,创建包装器函数
int wrapper_func(wrapper_st ^st, double x)
{
    sample_struct t;
    char *pp = (char*)Marshal::StringToHGlobalAnsi(st->cp).ToPointer();
    if (st->cp_valid)
        t.char_p = pp;
    else
        t.void_p = st->vp->ToPointer();
    t.a = st->a;
    // must ensure st->rsvd is not null, and length is 16!!!
    for (int i = 0; i < 16; ++i)
    {
        t.rsvd[i] = st->rsvd[i]->ToPointer();
    }
    int ret = sample_func(&t, x);
    Marshal::FreeHGlobal(IntPtr(pp));
    return ret;
}

那么,你可以使用c#中的包装器函数