I have a written a DLL in which I'm getting one of the paths:
//demo.h
__declspec(dllexport) void pathinfo(char * path);
Something is being done in the code to get this path. And now, the python script that I have written to retrieve this path from the DLL is as shown:
//demo.py
import sys
import ctypes
from ctypes import *
class demo(object):
def __init__(self):
self.demoDLL=CDLL("demo.dll")
def pathinfo(self):
path=c_char()
self.demoDLL.pathinfo.argtypes(POINTER(c_char))
self.demoDLL.pathinfo.result=None
self.demoDLL.pathinfo(byref(path))
return path.value
if __name__=='__main__':
abc=demo()
path_info=abc.pathinfo()
print "information of the path:",path_info
But the value that I'm able to see is just the first character of the path instead of the whole string.
Can anybody help me with this problem?
The reason you see only the first character is that by calling c_char()
you create a single char
value that Python treats like a str
(Python 2) object or bytes
(Python 3) object of length 1. You are probably lucky that you do not get a segmentation fault. By writing more than 1 byte or a NULL-terminated string of length > 0 (e.g. with strcpy
) in the C code, you actually produce an undetected buffer overflow. ctypes
does not know how many bytes you have written at the pointer's memory location. path.value
is still a str
/ bytes
of length 1.
It would be better to change the C pathinfo
function into someting like
size_t pathinfo(char* path, size_t bsize);
Use ctypes.create_string_buffer()
to allocate memory in your Python code and let pathinfo
return the length of the result. Of course you have to check, whether char* path
is large enough using bsize
in your C-Code.
The Python-code would look like this:
buf = ctypes.create_string_buffer(256)
result_len = pathinfo(buf, len(buf))
if result_len == len(buf):
# buffer may have been too short,
# try again with larger buffer
...
restlt_str = buf[0:result_len].decode('utf-8') # or another encoding
Also be aware of NULL-termination in the C domain, character encodings when converting python strings to char*
and back, the changes regarding str
/ bytes
in ctypes
regarding Python 2 and Python 3.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments