简体   繁体   English

PInvoke将来自ANSI C的结构指针编组为C#中的IntPtr

[英]PInvoke marshaling a struct pointer from ANSI C as an IntPtr in C#

So I'm trying to PInvoke an unmanaged DLL in C# from the iniParser library. 所以我试图从iniParser库PInvoke C#中的非托管DLL。 I'm currently stumbling over the correct way to marshal the struct pointers returned and taken by functions in the unmanaged library. 我目前正在绊倒正确的方法来编组非托管库中的函数返回和获取的结构指针。

In C: 在C:

__declspec(dllexport) dictionary * iniparser_load(const char * ininame);

In C#: 在C#中:

[DllImport("iniParser.dll")]
private static extern IntPtr iniparser_load(string filename);

The dictionary structure in C: C中的字典结构:

typedef struct _dictionary_ {
    int             n ;     /** Number of entries in dictionary */
    int             size ;  /** Storage size */
    char        **  val ;   /** List of string values */
    char        **  key ;   /** List of string keys */
    unsigned     *  hash ;  /** List of hash values for keys */
} dictionary ;

I understand that to actually access the structure in C# I need to create a counterpart for the C structure, but I don't need to access the struct in C#. 我理解为了实际访问C#中的结构,我需要为C结构创建一个对应物,但我不需要在C#中访问该结构。

When the function is called in C#, I get the following error: 在C#中调用该函数时,我收到以下错误:

A call to PInvoke function 'CacheExplorer!CacheExplorer.iniParser::iniparser_load'
has unbalanced the stack. This is likely because the managed PInvoke signature 
does not match the unmanaged target signature. Check that the calling convention 
and parameters of the PInvoke signature match the target unmanaged signature.

But how does the managed signature not match the unmanaged signature? 但是托管签名与非托管签名不匹配? Does PInvoke require that I make a C# counterpart for the C structure? PInvoke是否要求我为C结构制作C#对应物? All I need is essentially a handle to the dictionary in C#, accessing members is totally unnecessary and I'd rather not convert the structure to C# 我所需要的只是C#中字典的句柄,访问成员是完全没必要的,我宁愿不将结构转换为C#

iniParser库的调用约定可能是cdecl,这意味着您需要更新[DllImport]属性用法:

[DllImport("iniParser.dll", CallingConvention = CallingConvention.Cdecl)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM