I am trying to call C++ in python, here is my code:
hello.cpp
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
char* name;
name = argv[1];
std::cout << "hello," << name << std::endl;
return 0;
}
compile
g++ hello.cpp -o hello
g++ -shared -Wl,-soname,hello -o hello.so -fPIC hello.cpp
it works well in hello.exe
hello.exe world
hello,world
but when I calling hello.so in python, it returns an error:
python code
import ctypes as C
path = 'hello.so'
so = C.cdll.LoadLibrary
hello = so(path)
v1 = "world"
hello.main(v1)
error message
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_3516\3348774050.py in <module>
7
8 v1 = "world"
----> 9 hello.main(v1)
OSError: exception: access violation reading 0xFFFFFFFFFFFFFFFF
I have try to using ctypes.c_buffer or ctypes.c_bytes to change argument type, but it didn't work,
how can I pass the argument in correct way?
or how can I call C++ in python in correct way?
thanks
thanks to @Jean-François Fabre
I found the answer,the correct code should be
hello.main(2,v1)
It seems different from calling 'hello.exe', I thought that 'argv' was like 'self' and didn't need to be passed before
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.