-1

Here is my c# main

class Program
{
    static void Main(string[] args)
    {
        int i;
        unsafe
        {
        hdf_call_vars_t ret_vals;

        //IntPtr a ;
        //Marshal.PtrToStructure(a,ret_vals);

        ret_vals.fetch_nav = 1;
        string str = "C:\\DoAT\\a.h5";
        byte[] bytes = Encoding.ASCII.GetBytes(str);

            fixed (byte* p = bytes)
            {
                sbyte* sp = (sbyte*)p;
                //SP is now what you want
                DoAT.atrClass1 cl = new DoAT.atrClass1();

                cl.read_hdf5_file(sp,  ret_vals);

where the struct in c# is

[StructLayout(LayoutKind.Sequential, Pack = 1)]
/* Returned values from read_hdf5_file */
unsafe struct hdf_call_vars_t {
    public channel_vars p_vars; 
    public channel_vars s_vars; 
    FILE_VERSION file_vers; /* Set in top level sub. used in lower */
    public int fetch_nav; /* Boolean flag */
    public s_line_header_t * n_addr; /* malloc'd address of n data */
    public UInt32 n_lines;
    csdt_file_header_t hdr; 
};

this does not compile, says 'cl' needs as input a pointer to the hdf_call_vars_t.

In my c++ managed dll I have

int atrClass1::read_hdf5_file
    (const char * file_path, /* Path to  file */
     hdf_call_vars_t & ret_vals)

and also

struct hdf_call_vars {
    struct channel_vars p_vars; 
    struct channel_vars s_vars; 
    enum FILE_VERSION file_vers; /* Set in top level sub. used in lower */
    int fetch_n;     
    s_line_header_t * n_addr; /* malloc'd address of  data */
    unsigned int n_lines;
    csdt_file_header_t hdr; 
};
typedef struct hdf_call_vars hdf_call_vars_t;

Why does c# think a pointer needs to be sent into C++? If it is so, how do I make a pointer of the struct in the c# world?

4

1 回答 1

0

如果您的 C++ DLL 是托管的,为什么不将 atrClass1 标记为托管并避免所有 P/Invoke 混乱?

public ref class atrClass1
{
public:
    int read_hdf5_file(String^ file_path, hdf_call_vars^% ret_vals)
    {
        ...
    }
};

然后你可以直接从 C# 中使用它。

当然,您还需要 hdf_call_vars 的托管版本。您还应该使代码更加面向对象(避免使用当前 hdf_call_vars 等 POD 类型)。

于 2013-02-14T03:51:15.277 回答