提问人:unknown-889 提问时间:11/4/2023 最后编辑:Mark Tolonenunknown-889 更新时间:11/5/2023 访问量:42
共享库。C++ 与 Python
Shared Library. C++ with Python
问:
为什么我会遇到分段错误。
我想因为我使用的是字符串,但是我可以解决这个问题吗?
简单的代码,例如
#include <iostream>
#include <string>
struct Person {
int age;
std::string firstName;
std::string lastName;
std::string phoneNumber;
};
extern "C" {
Person* getPerson() {
Person person = Person();
person.age = 25;
person.firstName = "John";
person.lastName = "Doe";
person.phoneNumber = "123456789";
return new Person(person);
}
void deletePerson(Person* person) {
delete person;
}
}
from ctypes import cdll, Structure, c_char_p, c_int
person_lib = cdll.LoadLibrary('./lib.so')
class Person(Structure):
_fields_ = [
('age', c_int),
('firstName', c_char_p),
('lastName', c_char_p),
('phoneNumber', c_char_p)
]
person_lib.getPerson.restype = Person
person_lib.deletePerson.argtypes = [Person]
person = person_lib.getPerson()
info = f"Name: {person.firstName} {person.lastName}\nAge: {person.age}\nPhone: {person.phoneNumber}"
print(info)
person_lib.deletePerson(person)
希望从 c++ 库中获取一些信息并在 python 中使用它
答: 暂无答案
评论
c_char_p
std::string
char* (NUL terminated)
Person
std::string
const char*
ctypes