0

I have the following simple C function:

void pyentry(const char *config)
{
    printf("%s\n",config);
    fflush(stdout);
}

My ctypes definition is as follows:

libc = ct.CDLL("./amr.so")
entry = wrap_function(libc, 'pyentry', ct.POINTER(Checkpoint), [ct.c_wchar_p])
json = "this is a test"
start = entry(json)

Where wrap_function is simply a wrapper for more easily defining ctypes access to C functions:

def wrap_function(lib, funcname, restype, argtypes):
    func = lib.__getattr__(funcname)
    func.restype = restype
    func.argtypes = argtypes
    return func

I have compiled as a shared library and I am trying to call it, but in C it is only printing the first character of the string I send in. I am assuming this is because I have the wrong argument tpyes in my ctypes definition, but I am not having any luck figuring out out the right one.

Can someone tell me why my C function is only seeing the first character in the passed string?

3
  • 2
    Hint: what's the difference between char and wchar_t? Commented Feb 23, 2021 at 20:21
  • 1
    I managed to get it working using ct.POINTER(ct.c_char) as the type. Thanks for the hint. I do not know why I didn't start with that. Commented Feb 23, 2021 at 20:32
  • 1
    pyentry is void, so .restype shoud be None. .argtypes shoudl be [ct.c_char_p]. getattr(lib,funcname) is more Pythonic. start = entry(json) should just be entry(json). Commented Feb 23, 2021 at 21:44

1 Answer 1

1

Try:

entry = wrap_function(libc, 'pyentry', None, [ct.POINTER(ct.c_char)])
json = "this is a test".encode('utf-8')

pyentry takes const char* and returns void. So argtypes and restype could be [ct.POINTER(ct.c_char)] and None.

And char* points a sequence of bytes, not Python string. So json should be converted to bytes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.