让我们假设我们从某个外部库中获得了一个名为chr_ptr的char*。
我尝试使用cppyy.ll.cast"char*"将这个指针转换为char*
预期:cppyy.LowLevelView
实数:str
其他数据类型运行良好,此问题只会发生char(a.k.a )。int8_t)。转换指针(比方说) int16_t是可以的。
import cppyy
import cppyy.ll
if not hasattr(cppyy.gbl, "get_char_pointer"):
cppyy.cppdef("""
void* get_char_pointer()
{
char a = 1;
return &a;
}
""")
if not hasattr(cppyy.gbl, "get_uint16_t_pointer"):
cppyy.cppdef("""
void* get_uint16_t_pointer()
{
uint16_t a = 1;
return &a;
}
""")
if not hasattr(cppyy.gbl, "print_address"):
cppyy.cppdef("""
void print_address(void* p)
{
std::cout << "address is: " << p << std::endl;
}
""")
char_ptr = cppyy.gbl.get_char_pointer()
uint16t_ptr = cppyy.gbl.get_uint16_t_pointer()
cppyy.gbl.print_address(char_ptr)
cppyy.gbl.print_address(uint16t_ptr)
casted_char_ptr = cppyy.ll.cast["char*"](char_ptr) # At this point expected cppyy.LowLevelView but I got str
casted_uint16t_ptr = cppyy.ll.cast["uint16_t*"](uint16t_ptr)
print()
print(type(casted_char_ptr))
print(type(casted_uint16t_ptr))
print()
try:
cppyy.gbl.print_address(casted_char_ptr)
except TypeError as err:
print(err)
cppyy.gbl.print_address(casted_uint16t_ptr)结果是:
address is: 0x7fff58b64847
address is: 0x7fff58b64846
<class 'str'>
<class 'cppyy.LowLevelView'>
void ::print_address(void* p) =>
TypeError: could not convert argument 1
address is: 0x7fff58b64846发布于 2022-03-21 18:35:28
是的,char*是那些仅基于反射信息的类型之一,在其预期用途中并不清楚。有一个半成品的修补程序可以修复函数/数据成员,使其具有其独特的char*含义,所以这就来了,是的,cast()是一个很明显的例子,char*更可能是byte*而不是C-string,所以应该将其作为默认值。
尽管如此,在这种情况下,实际使用std::byte* (如果不使用C++17)来指示结果应该是什么应该是好的:
casted_char_ptr = cppyy.ll.cast["std::byte*"](char_ptr) 它根据需要生成LowLevelView。
编辑:signed byte的解决方案
cppyy.cppdef("enum signed_byte : signed char;")
casted_char_ptr = cppyy.ll.cast["signed_byte*"](char_ptr)
casted_char_ptr[0] = -1https://stackoverflow.com/questions/71555655
复制相似问题