c# - 如何将结构指针从 c# 传递到 win32 DLL

标签 c# c++ dll struct arrays

我想将字节数组从 C# 传递到 win32 DLL 以用于 c++ 中的某些进程!

我的C++代码

    typedef struct
    {
        int length;
         unsigned char value[10000000];
    } wavfile;

    extern "C" __declspec(dllexport) int insert_In_Table(wavfile *w)
   {

    hashing HS( w->value , (unsigned int)w->length);

        return HS.insertIn_hashTable();
    }

和我的 C#

[DllImport("HashCplusDll.dll" , CallingConvention=CallingConvention.Cdecl)]
public static extern int insert_In_Table(ref Wavfile sample);
public static int recordNumber_old = 0;

public struct Wavfile
{

    public int length;
    [MarshalAs(UnmanagedType.LPArray, SizeConst = 10000000)]
    public byte[] value;
}

public void button1_Click(object sender, EventArgs e)
{
    // open file dialog 
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "All files (*.*)|*.*"; 
    if (open.ShowDialog() == DialogResult.OK)
    {

        string location = open.FileName;
        byte[] array = System.IO.File.ReadAllBytes(location);
        textBox1.Text = location;

        Wavfile pass = new Wavfile();
        pass.value = array;
        pass.length = array.Length;
        int numberOfRow = insert_In_Table(ref pass);
    }

但是我有这个错误

A first chance exception of type 'System.TypeLoadException' occurred in WindowsFormsApplication1.exe

Additional information: Cannot marshal field 'value' of type 'Wavfile': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).

If there is a handler for this exception, the program may be safely continued.

我尝试了一些解决方案,例如 out 而不是 ref 但还是无法运行应用。

我该怎么办?

最佳答案

由于 MarshallAs 的 meta 属性,它正在提示。您需要将其更改为 ByValArray。

使用 UnmanagedType.ByValArray 而不是 UnmanagedType.LPArray

关于c# - 如何将结构指针从 c# 传递到 win32 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28764634/

相关文章:

c++ - 将元素插入排序 vector 并保持元素排序

c# - 为什么在 C# 中使用 float.NaN != double.NaN?

c++ - boost 文件系统中的段错误?

c++ - 处理设定间隔的算法

php 为什么我找不到类 'Thread'

c - C appln 中的 dlopen 和 dlclose 内存管理

c# - 如何获取 List<of anonymous type> 字段的值(加上转换)?

c# - 如何恢复 ObservableCollection 的更改值?

c# - 如何解析 Json.NET 多态对象?

windows - 只为一个进程初始化一次临界区