简体   繁体   English

在ctypes中使用dll函数 python 2.7与3.6

[英]Use dll-function in python with ctypes | python 2.7 vs. 3.6

I have a C++-Library (example.dll) with some functions and want to use them from Python. 我有一个带有某些功能的C ++库(example.dll),想从Python使用它们。 I got it working with ctypes and Python 2.7, but not with Python 3.6. 我可以使用ctypes和Python 2.7,但不能使用Python 3.6。

Here an excerpt from example.h : 这是example.h的摘录:

extern "C" __declspec(dllexport) LONG _stdcall func1(LPTSTR filename, long cbAddress);

The function is parsing a txt-file, loads some data to the memory and returns a handle to this data. 该函数正在解析txt文件,将一些数据加载到内存中并返回该数据的句柄。

My code for Python 2.7 is: 我的Python 2.7代码是:

from ctypes import *

mydll = WinDLL(r'C:\temp\example.dll')
txt_path = c_char_p(r'C:\temp\file.txt')

func1 = mydll['func1']
func1.restype = c_long
func1.argtypes = (c_char_p , c_void_p)
handle = func1(txt_path, None)

This is working and returns a valid handle. 这正在工作并返回有效的句柄。

With Python 3.6, line 3 causes an error: 使用Python 3.6,第3行会导致错误:

>>> txt_path = c_char_p(r'C:\temp\file.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bytes or integer address expected instead of str instance

so I changed it to 所以我改成

txt_path = c_char_p(b'C:\temp\file.txt')

which is working, but leads to a problem with the function. 这是可行的,但导致功能出现问题。 func1 returns now 0, which is an intern error code for "could not read txt-file." func1现在返回0,这是“无法读取txt文件”的内部错误代码。

I tried to use different types, but it didn't work and I'm kind of stuck now. 我尝试使用其他类型,但没有用,现在有点卡住了。

Can anyone help? 有人可以帮忙吗?

问题只是转义了反斜杠(有些愤世嫉俗的人可能说这是Windows),必须将有问题的行txt_path = c_char_p(b'C:\\temp\\file.txt')更改为:

txt_path = c_char_p(b'C:\\temp\\file.txt')

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

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