ctypes.cast() is used to convert one ctype instance to another ctype datatype. You don't need it To convert it to python string. Just use ".value" to get it in python string.

>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> print c_s.value
Hello, World

More info here

Answer from Rajendran T on Stack Overflow
🌐
Python
python-list.python.narkive.com › pJK2bMLY › ctypes-delay-conversion-from-c-char-p-to-string
ctypes: delay conversion from c_char_p to string
Note that tmp_char_ptr is of type c_void_p. This should avoid the memory leak, assuming I am interpreting the semantics of the cast correctly. Is there a cleaner way to do this with ctypes? def get_prop_string(self, prop_name): # Have to work with c_void_p to prevent ctypes from copying to a string # without giving me an opportunity to destroy the original string.
🌐
ProgramCreek
programcreek.com › python › example › 1243 › ctypes.c_char_p
Python Examples of ctypes.c_char_p
""" size = ctypes.c_uint() sarr ... return [py_str(sarr[i]) for i in range(size.value)] ... def c_str_array(strings): """Create ctypes const char ** from a list of Python strings....
🌐
Python
svn.python.org › projects › ctypes › tags › before_LoadLibrary_branch › ctypes › docs › manual › tutorial.txt
ctypes tutorial +++++++++++++++
Other return types can be specified by setting the ``restype`` attribute of the function object. Here is a more advanced example, it uses the strchr function, which expects a string pointer and a char, and returns a pointer to a string:: >>> from ctypes import * >>> strchr = cdll.msvcrt.strchr >>> strchr("abcdef", ord("d")) # doctest: +SKIP 8059983 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string >>> strchr("abcdef", ord("d")) 'def' >>> print strchr("abcdef", ord("x")) None >>> If you want to avoid the ``ord("x")`` calls above, you can set the ``argtypes`` attribute, and the s
Top answer
1 of 2
17
from ctypes import *

charptr = POINTER(c_char)

test = CDLL('test.so')
test.initializetest.argtypes = []
test.initializetest.restype = charptr
test.searchtest.argtypes = [charptr]
test.searchtest.restype = c_int

buf = test.initializetest()
test.searchtest(buf)
print cast(buf, c_char_p).value
# TODO Release the "buf" memory or it will leak.

EDIT

Initially I used c_char_p to pass the buffer between the functions but c_char_p is like a const pointer. If used as a restype, you will actually get a Python str back. So for initializetest it will create a string from the allocated memory (by copying data) and throw the pointer away.

Now we're creating a new type, a POINTER to c_char. This is then used in both functions.

For Python, this type points to a single char so we have to cast it to get the whole string after searchtest is done. We cast to c_char_p because we just want to read the value so a const pointer is OK.

As a side note, this illustrates the disastrous effect of using c_char_p with functions that modify the array (as searchtest above does):

>>> libc.memset.argtypes = [c_char_p, c_int, c_int]
>>> foo = 'Python'
>>> foo
'Python'
>>> libc.memset(foo, ord('x'), 3)
44808532
>>> foo
'xxxhon'
>>>

Note how we've managed to change an immutable Python string!

The argtypes setup line isn't even needed because ctypes assumes c_char_p if Python str is used as argument.

2 of 2
1

Maybe by using restype like described here

class Test(object):
    def __init__(self):
        self.test_library=CDLL("./test.so")
        self.test_initialize = self.test_library.initializetest
        self.test_initialize.argtypes = []
        self.test_initialize.restype = c_char_p # c_char_p is a pointer to a string
        self.test_search = self.test_library.searchtest
        self.test_search.restype = c_int
        self.test_search.argtypes = [c_char_p]
        self.m = c_char_p(self.test_initialize())

    def search(self):
        return self.test_search(self.m).value

r = Test()
print r.search()

EDIT: corrected after test :)

🌐
CodersLegacy
coderslegacy.com › home › python › python ctypes tutorial
Python ctypes Tutorial - CodersLegacy
October 27, 2022 - Before: c_char_p(2200599049040) b'Hello' After: c_char_p(2200599049040) b'Ifmmp' As you can see, the string was properly modified. Creating a string buffer with ctypes, gives us mutable memory which we can use with C functions.
Find elsewhere
🌐
docs.python.org
docs.python.org › 3 › library › ctypes.html
ctypes — A foreign function library for Python
By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object. The C prototype of time() is time_t time(time_t *). Because time_t might be of a different type than the default return type int, you should specify the restype attribute: ... Here is a more advanced example, it uses the strchr() function, which expects a string pointer and a char...
🌐
Python
python.supply › working-with-foreign-functions
working-with-foreign-functions
The C function fopen expects two arguments: a pointer to the first character of a string that represents the path of the file, and a pointer to the first character of the string that represents the mode (i.e., reading or writing) in which the file is opened. You can use the c_char_p function to turn Python strings into a representation in memory that can be handled by the C function.
🌐
BestDivision
bestdivision.com › spread your knowledge - bestdivision › questions - bestdivision › python questions - categories - bestdivision › how to convert a python string to c_char_p in ctypes? - bestdivision
How to convert a Python string to c_char_p in ctypes? | BestDivision
July 15, 2023 - This conversion ensures that the Python string is correctly passed as a char * argument. Suppose you have a simple C library function that takes a string and prints it: To call this function from Python using ctypes, you can follow these steps: Compile the C code into a shared library (example.so on Linux or example.dll on Windows).
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
utf-8 and ctypes | Python | Coding Forums
September 30, 2010 - I'm using python 2.5. Currently I have some python bindings written in ctypes. On the C side, my strings are in utf-8. On the python side I use ctypes.c_char_p to convert my strings to python strings. However, this seems to break for non-ascii characters. It seems that characters not in the...
Top answer
1 of 1
26

c_char_p is a subclass of _SimpleCData, with _type_ == 'z'. The __init__ method calls the type's setfunc, which for simple type 'z' is z_set.

In Python 2, the z_set function (2.7.7) is written to handle both str and unicode strings. Prior to Python 3, str is an 8-bit string. CPython 2.x str internally uses a C null-terminated string (i.e. an array of bytes terminated by \0), for which z_set can call PyString_AS_STRING (i.e. get a pointer to the internal buffer of the str object). A unicode string needs to first be encoded to a byte string. z_set handles this encoding automatically and keeps a reference to the encoded string in the _objects attribute.

>>> c = u'spam'
>>> a = c_char_p(c)
>>> a._objects
'spam'
>>> type(a._objects)
<type 'str'>

On Windows, the default ctypes string encoding is 'mbcs', with error handling set to 'ignore'. On all other platforms the default encoding is 'ascii', with 'strict' error handling. To modify the default, call ctypes.set_conversion_mode. For example, set_conversion_mode('utf-8', 'strict').

In Python 3, the z_set function (3.4.1) does not automatically convert str (now Unicode) to bytes. The paradigm shifted in Python 3 to strictly divide character strings from binary data. The ctypes default conversions were removed, as was the function set_conversion_mode. You have to pass c_char_p a bytes object (e.g. b'spam' or 'spam'.encode('utf-8')). In CPython 3.x, z_set calls the C-API function PyBytes_AsString to get a pointer to the internal buffer of the bytes object.

Note that if the C function modifies the string, then you need to instead use create_string_buffer to create a c_char array. Look for a parameter to be typed as const to know that it's safe to use c_char_p.

🌐
Numba Discussion
numba.discourse.group › community support
Accelerate loops that use ctypes, c_char_p, numpy str_? - Community Support - Numba Discussion
June 13, 2020 - I wrote a python library that wraps a c shared-library with over 600 functions using pure ctypes and numpy. The functions are typically simple, say given a string return a float, and for some functions I allow users to p…
🌐
Python.org
discuss.python.org › python help
Dealing with char*** in ctypes - Python Help - Discussions on Python.org
December 13, 2023 - I have this function in C library that I want to access from python using ctypes: static const char *names[] = {"Backplane", "ADC", "External", "Reserved"}; int test_char_ptr(const char ***names_, int *count_) { …
🌐
GitHub
github.com › aquynh › capstone › issues › 557
Python 3 support: Bind `str` to `c_wchar_p` instead of `c_char_p` · Issue #557 · capstone-engine/capstone
December 1, 2015 - Cause: CsError's __str__ function returns a bytes (Python 2 non-unicode string) instead of a str (Python 3 unicode string). Python 3 requires that __str__ returns a str. Solution: When setting up the functions in __init__.py, use ctypes.c_wchar_p if it's Python 3. PS: There are also three other functions in __init__.py which return c_char_p.
Author: capstone-engine
🌐
Intel Community
community.intel.com › t5 › Intel-Fortran-Compiler › Passing-by-reference-a-Python-string-to-Fortran-function › m-p › 1297543
Re: Passing (by reference) a Python string to Fortran function (subroutine) - Intel Community
July 11, 2021 - The in_str name in Python goes out of scope, is explicitly unbound using `del` or is bound to something else. If no further references to the previously bound c_char_p object exist, then Python will [eventually] delete it, if no other references exist to the byte string, Python will [eventually] delete that.
🌐
Runebook.dev
runebook.dev › en › docs › python › library › ctypes › ctypes.c_char_p
Working with C Strings in Python: Tips for ctypes.c_char_p
October 23, 2025 - Before passing a Python str to a C function via c_char_p, you must encode it into a bytes object, usually using a standard encoding like UTF-8 or ASCII. import ctypes # 1. Python string (str) python_str = "Hello ctypes!" # 2. Encode to bytes using .encode() # (UTF-8 is the standard recommendation) encoded_bytes = python_str.encode('utf-8') # 3.