在C#中将结构指针作为参数传递 [英] Passing a struct pointer as a parameter in C#
问题描述
我在C ++中有一个导出到DLL的函数.我包含一个结构指针作为参数之一.我需要在C#中使用此函数,因此我将DLLImport用于该函数,并使用StructLayout在C#中重新创建了结构.我尝试使用ref传递参数,并尝试使用MarshalAs(UnmangedType.Struct)和Marshal.PtrToStructure封送它.参数仍然没有正确传递.
I have a function in C++ that I exported to a DLL. I contains a struct pointer as one of the parameters. I need to use this function in C#, so I used DLLImport for the function and recreated the struct in C# using StructLayout. I've tried passing in the parameter using ref as well as tried Marshaling it in using MarshalAs(UnmangedType.Struct) and Marshal.PtrToStructure. The parameter still isn't passing correctly.
示例:
[DllImport("testdll.dll")]
public static extern int getProduct(int num1, int num2, [MarshalAs(UnmanagedType.Struct)] ref test_packet tester);
信息的另一个花哨之处是,该结构包含一个byte * var,我认为这可能会导致将参数作为ref传递的问题.有任何想法吗?我在正确的轨道上吗?感谢您的帮助.
One more tidbit of info, the struct contains a byte* var, which I think may be causing the problem in terms of passing the param as ref. Any ideas? Am I on the right track? Thanks for the help.
感谢nobugz的响应.这是struct def的示例:
Thanks nobugz for the response. Here's a sample of the struct def:
//C# DEFINITION
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct test_packet
{
public UInt32 var_alloc_size;
public byte* var;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_TAG_LENGTH)]
public byte[] tag;
}
//ORIGINAL UNMANAGED STRUCT
typedef struct test_packet_tag
{
unsigned int var_alloc_size;
unsigned char *var;
unsigned char tag[MAX_TAG_LENGTH];
} test_packet;
推荐答案
使用"ref"是正确的方法,摆脱[MarshalAs]属性.真正的问题几乎可以肯定是结构声明.您没有发布任何有助于我们帮助您的内容.
Using "ref" is the correct way, get rid of the [MarshalAs] attribute. The real problem is almost certainly the structure declaration. You didn't post anything that would help us help you with that.
DllImportAttribute.CharSet属性错误,将其设置为CharSet.Ansi.将"var"成员声明为错误,将其设置为byte [].请确保在调用之前对其进行初始化:
The DllImportAttribute.CharSet property is wrong, make it CharSet.Ansi. The "var" member is declared wrong, make it byte[]. Be sure to initialize it before the call:
var product = new test_packet();
product.var_alloc_size = 666; // Adjust as needed
product.var = new byte[product.var_alloc_size];
int retval = getProduct(42, 43, ref product);
最好的猜测,希望它能起作用.
Best guess, hope it works.
这篇关于在C#中将结构指针作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!