我想将字节数组从 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/