python - c 指针和 ctypes

标签 python c++ c ctypes

因此,我将 C++ 类包装在 C 中,这样我就可以使用 ctypes 在 Python 中使用它。 C++类声明:

// Test.h
class Test
{
public:
   static double Add(double a, double b);
};


//Test.cpp
#include "stdafx.h"
#include "Test.h"

double Test::Add(double a, double b)
{
   return a + b;
}

C 换行:

// cdll.h
#ifndef WRAPDLL_EXPORTS
#define WRAPDLL_API __declspec(dllexport) 
#else
#define WRAPDLL_API __declspec(dllimport) 
#endif

#include "Test.h"
extern "C"
{
   WRAPDLL_API struct TestC;

   WRAPDLL_API TestC* newTest();
   WRAPDLL_API double AddC(TestC* pc, double a, double b);
}

//cdll.cpp
#include "stdafx.h"
#include "cdll.h"

TestC* newTest()
{
   return (TestC*) new Test;
}

double AddC(TestC* pc, double a, double b)
{
   return ((Test*)pc)->Add(a, b);
}

Python 脚本:

import ctypes
t = ctypes.cdll('../Debug/cdll.dll')
a = t.newTest()
t.AddC(a, 2, 3)

t.AddC(a, 2, 3) 的结果总是一些负整数。 指针有问题,但我不知道是什么问题。 有人有什么想法吗?

最佳答案

因为 AddC 是一个静态函数,所以指针不是您的问题。

您需要将double 值传递给AddC,并返回一个double 类型:

t.AddC.restype = c_double
t.AddC(a, c_double(2), c_double(3))

documentation for ctype解释了这一切。

关于python - c 指针和 ctypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457079/

相关文章:

python - SQLAlchemy:如何为列的析取创建混合属性?

python - BeautifulSoup 和表格行内的换行符?

c++ - 简单的输入/输出控制台应用程序,不按给定顺序打印问题(结构性)

c - 为什么当多个 pthread 竞争互斥锁时 PTHREAD_MUTEX_ADAPTIVE_NP 表现得像 PTHREAD_MUTEX_TIMED_NP

c - linux编程: write to device file

python - Pandas:行和列总和的外积

python - python中for循环中的两个变量

c++ - LevelDB:比较器、block_cache 和 filter_policy 的生命周期和职责?

c++ - 在编译期间操作字符串的 C/C++ 宏

C Big Endian 到 Little Endian 结构