问题描述
还有另一个我的P/调用问题!我有这个C函数:
Yet another one of my P/Invoke questions! I have this C function:
int _ei_x_new(ei_x_buff* x);
本质上,它将初始化一个新的缓冲区结构.在C#中,我有这个:
Essentially, it initializes a new buffer struct. In C#, I have this:
[DllImport(EIDLL, EntryPoint = "_ei_x_new")]
public static extern int ei_x_new(out ei_x_buff x);
ei_x_buff
非常简单:
typedef struct ei_x_buff_TAG {
char* buff;
int buffsz;
int index;
} ei_x_buff;
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ei_x_buff {
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string buff;
public int buffsz;
public int index;
}
但是当我这样做时:
ei_x_buff buffer;
Ei.ei_x_new(out buffer);
我收到一个 AccessViolationException :
我需要分配一些内存吗?这是一段简单的代码,我看不到任何明显的问题.
Do I need to alloc some memory or something? It's such a simple piece of code that I can't see any glaring problems with it.
_ei_x_new
的本地代码:
// In my wrapper library
DLL_EXPORT int _ei_x_new(ei_x_buff* x) {
return ei_x_new(x);
}
// In external library being wrapped
int ei_x_extra = 100;
int ei_x_new(ei_x_buff* x)
{
x->buff = malloc(ei_x_extra);
x->buffsz = ei_x_extra;
x->index = 0;
return x->buff != NULL ? 0 : -1;
}
推荐答案
事物的结合
- 要在双向(进出本机函数)中整理数据,请在PInvoke签名中使用not ref
- 您能否发布本机签名,因为它们可能是定义问题.特别是buff成员
编辑
只是为了消除一种可能性,请将buff成员切换为没有属性的IntPtr类型.如果这不会导致崩溃,则可能是字符串类型存在编组问题.
Just to eliminate one possibility, switch the buff member to be typed IntPtr with no attributes. If that doesn't cause a crash then it's likely a marshalling issue with the string type.
这篇关于通过引用传递结构导致AccessViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!