我想在 Windows 上使用 Python3 从外部 dll 调用一些函数。我要使用的库和功能如下;
MECAB_DLL_EXTERN mecab_t* mecab_new2(const char *arg);
MECAB_DLL_EXTERN const char* mecab_sparse_tostr(mecab_t *mecab, const char *str);
MECAB_DLL_EXTERN void mecab_destroy(mecab_t *mecab);
我需要先调用mecab_new2
,从它的返回中获取指针并使用它mecab_sparse_tostr
,然后最后通过调用使用相同的指针来处理它mecab_destroy
。
我发现以下在 C# 中有效(如果它有助于作为参考):
[DllImport(@"C:\libmecab.dll", CallingConvention = CallingConvention.Cdecl)]
private extern static IntPtr mecab_new2(string arg);
[DllImport(@"C:\libmecab.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private extern static IntPtr mecab_sparse_tostr(IntPtr m, byte[] str);
...
{
IntPtr mecab = mecab_new2("-Owakati"); // returns a pointer
mecab_sparse_tostr(mecab, Encoding.UTF8.GetBytes(input));
但无法在 python 中找到类似的方法。我已经尝试了以下不同的 restypes 和 argtypes。但是该mecab_new2
函数总是返回 0(我假设它为空?)。
import ctypes
mecab_dll = ctypes.WinDLL(r"C:\libmecab.dll")
mecab_new2 = mecab_dll['mecab_new2']
mecab_new2.restype = ctypes.POINTER(ctypes.c_int)
mecab_new2.argtypes = [ctypes.c_char_p]
p1 = ctypes.c_char_p(b"-Owakati")
res = mecab_new2(p1)
print(res.contents)
# ValueError: NULL pointer access
如果我删除 restype 参数,它返回 0,restype = ctypes.POINTER(ctypes.c_int)
它返回一个空指针。
我浏览了类似的问题和文档,但找不到方法。C++ 非常糟糕,因此 ctypes 也是如此。
谢谢。
编辑:我已经尝试了库中的另一个函数,一个不需要任何参数并且运行正确的函数。所以我假设我的问题在于参数不匹配?或者图书馆不知何故坏了?
头文件:
MECAB_DLL_EXTERN const char* mecab_version();
Python代码:
mecab_ver = mecab_dll["mecab_version"]
mecab_ver.restype = ctypes.c_char_p
print(mecab_ver()) # returns b'0.996' which is correct