简体   繁体   English

痛饮通过 Python 日期时间 object 到 C++

[英]Swig pass Python datetime object to C++

I have a function in C++ that is passed a uint64_t as nanoseconds from epoch.我在 C++ 中有一个 function ,它从纪元开始以纳秒的形式传递了一个uint64_t I have wrapped this number in an object DateTime as in我已将此号码包装在 object DateTime中,如

struct DateTime {
    uint64_t epochns;
};
void print( DateTime ts );

Obviously the function is not exactly print as I could use Python's own for this purpose.显然 function 并不完全是print的,因为我可以为此目的使用 Python 自己的。

It is important that I use it seamlessly with Python datetime objects as in重要的是我将它与 Python 日期时间对象无缝使用,如

print( datetime(1985,7,1) )

I'm unsure how to write a typemap that achieves this requirement.我不确定如何编写满足此要求的类型图。

Any hints?有什么提示吗?

Call the method datetime.timestamp on the object to return the epoch in seconds then multiply by 1E6 to get to microseconds and round to integer.调用 object 上的方法datetime.timestamp以秒为单位返回纪元,然后乘以 1E6 得到微秒并舍入到 integer。 Then multiply again by 1000 to get to nanoseconds.然后再乘以 1000 得到纳秒。

%typemap(in)  DateTime
{
    PyObject* str = PyString_FromString( "timestamp" );
    PyObject* obj = PyObject_CallMethodObjArgs( $input, str, nullptr );
    $1.epochns = int64_t(PyFloat_AsDouble( obj )*1000000)*1000LL;
    Py_XDECREF( obj );
    Py_XDECREF( str );
}

The intermediate multiplication is necessary as if you multiply straight by 1E9 you will have unrounded garbage in the nanoseconds part.中间乘法是必要的,就像你直接乘以 1E9 一样,你将在纳秒部分有未舍入的垃圾。

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

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