Freetype .net包装器问题(试图编写受保护的内存异常)

时间:2012-04-05 19:38:20

标签: .net freetype2

我正在尝试为.net设置freetype2而我仍然不够幸运。所以我使用this question的答案。目前我尝试使用Init_FreeType函数,我得到一个异常,我试图写入受保护的内存。我使用的代码如下:

Intptr library = new Intptr();
FreeType.FT.Init_FreeType(library);

包装器中的Init_FreeType函数声明如下:

[DllImport(FT_DLL, EntryPoint = "FT_Init_FreeType"), SuppressUnmanagedCodeSecurity]
public static extern int Init_FreeType(IntPtr /*IntPtr LibraryRec_*/ alibrary);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在我看来,Init_FreeType的声明是错误的。应该是:

public static extern int Init_FreeType(ref IntPtr alibrary);

(参数为ref)。并称之为:

IntPtr library = IntPtr.Zero;
FreeType.FT.Init_FreeType(ref library);

我怀疑发生了什么Init_FreeType将传递的值视为参考并尝试将库句柄存储在该内存位置。但是,由于你传递了指针的(而不是指针位置),它会进入杂草。

回复评论的进一步信息:

FT_Init_FreeType的文档将其定义为:

FT_EXPORT( FT_Error ) FT_Init_FreeType( FT_Library  *alibrary );

FT_ErrorintFT_Library

typedef struct FT_LibraryRec_  *FT_Library;

所以你肯定需要通话时ref。托管原型应如上所示。

堆栈不平衡几乎肯定是由错误的调用约定引起的。在.NET中,默认调用约定是stdcall。在我看来FreeType正在使用cdecl调用约定。所以你的DllImport应该是:

[DllImport(FT_DLL, EntryPoint="FT_Init_FreeType", 
    CallingConvention=CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]