简体   繁体   English

传递Python元组代替C ++ struct函数参数是否会对性能产生影响?

[英]Are there any performance implications of passing a Python tuple in place of a C++ struct function argument?

I would like to make use of a couple of C++ libraries from within Python to provide a Python API for scripting a C++ application. 我想利用Python中的几个C ++库来提供用于编写​​C ++应用程序脚本的Python API。 So I am wondering if there are any performance implications of passing a Python tuple in place of a C++ struct to a C++ function? 因此,我想知道将Python元组代替C ++结构传递给C ++函数是否会对性能产生影响? Also, are the two data structures the same? 另外,两个数据结构是否相同? If the two are the same, how can I prevent a tuple with incompatible member types from being passed? 如果两者相同,如何防止成员类型不兼容的元组通过? Would that impact the performance? 这会影响性能吗? If that impacts performance, what are the best practices for dealing with such situations in Python. 如果这会影响性能,那么在Python中处理此类情况的最佳实践是什么。 Please note that I am clearly not the author of the libraries. 请注意,我显然不是库的作者。

There's almost no relationship between a Python tuple and a struct in C++. Python元组和C ++中的struct之间几乎没有关系。 The elements of a tuple are neither named nor typed, and must be accessed (in C++) through functions in the Python C API ( PyTuple_GetItem , etc.). 元组的元素既没有命名也没有类型,必须通过Python C API中的函数( PyTuple_GetItem等)进行访问(在C ++中)。 Internally (although you don't have access to it directly), a tuple is an array of pointers to objects. 在内部(尽管您不能直接访问它),元组是指向对象的指针数组。 Even for types like int and float . 即使对于intfloat这样的类型。

Because of the function calls and the added levels of indirection, using a Python tuple will be slower than using a struct . 由于函数调用和增加的间接级别,使用Python元组将比使用struct慢。 The "best practice" is to write a wrapper function, which extracts the information from the tuple, doing the dynamic type checking, etc., and use it to initialize the struct which you then send on the the C++ function. “最佳实践”是编写一个包装函数,该函数从元组中提取信息,进行动态类型检查等,并使用它来初始化struct ,然后在C ++函数上发送该struct There's really no other way. 真的没有其他办法了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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