-3

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

hljjj
  • 21
  • 3
  • 3
    the number of arguments of `main` doesn't match... the types don't match either – Jean-François Fabre Dec 21 '22 at 19:52
  • 3
    Why would you pass a single `char*` to a function whose arguments are `int argc, char * argv[]`? What are you expecting to happen? – Random Davis Dec 21 '22 at 19:54
  • the reasaom of using "main(int argc, char * argv[])" instead of "main(char name)" is when I using "main(char name)" will return warnning " first argument of 'int main(char)' should be 'int' [-Wmain]" and "'int main(char)' takes only zero or two arguments [-Wmain]" – hljjj Dec 21 '22 at 20:36
  • [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/a/58611011/4788546). Also *main* is usually the entrypoint of a program, not of a shared object. – CristiFati Dec 21 '22 at 22:05

1 Answers1

-1

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

hljjj
  • 21
  • 3