简体   繁体   中英

How save a C++ pointer in python to pass it again later?

I'm trying to create something and I don't know if it's possible or "clean":

  1. From python, call function A of my C++ code to compute something complicated
  2. The C++ code returns just the pointer to the python
  3. Do other things in python...
  4. From python, call function B of my C++ code, it takes the pointer and other things as arguments.

I really don't need to use my complicated C++ class in my Python algorithm, that's why I just want to save the pointer in python.

Anyone has any advice on how to do that?

Edit: In the end I wrapped the c++ class in python, thank you everyone.

A pointer is just data that can be marshaled and sent to anything. It is however a very bad idea because when doing that, you have to assure that that pointer remains valid as long as the python part has the pointer. There is no possibility to check whether the pointer is still valid, so dereferencing a pointer that you receive from an external party could crash your program.

A better idea in a lot of situations is to send a key to a table. When that key is sent back, it can be used to get the needed information from that table and it can be handled when the table doesn't have the key anymore. It is easiest to use std::map for the table. Of course, you could store the pointer in a container and check for that, but a string or number is easier to debug.

It would be better to create a class in C++ and store that pointer in the class itself as private. Then create function calls to access those pointers.

Once the class is implemented generate the.so file of your lib and import it in python. This way you can simply use your C++ code in python and also will not have to save the pointer.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM