1

fib.cpp

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
using namespace std;

extern "C" const char *hello (char* b){
static string s = "hello ";
s = s + b;
return s.c_str();
}

wrap.py

import ctypes
_libfib = ctypes.CDLL('./fib.so');

def ctypes_hello(a):
    _libfib.hello.restype = ctypes.c_char_p;
    return _libfib.hello(ctypes.c_char_p(a));

Generate .so files

g++ -std=c++11 -shared -c -fPIC fib.cpp -o fib.o
g++ -std=c++11 -shared -Wl,-soname,fib.so -o fib.so fib.o

Run wrap.py from command line

from wrap import *
ctypes_hello("world")

Its working perfectly with python 2. I am getting Error bytes or integer address expected instead of str instance when I switch to Python 3

0

1 Answer 1

2

Python 3 differentiates between byte strings and unicode strings. So in Python 3 your "world" string is a sequence of Unicode code points, not a simple byte string. So in Python 3 try:

ctypes_hello(b"world")

To pass a byte string to the function.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.