CPPYY include 和 load_libraries及动态特性(二)

CPPYY Part II

动态特性

我们来实现一个简单的KNN算法

"""
新建一个文件 nearest_neighbors.h
------------------
#pragma once

#include 
#include 

class Point {
public:
  Point() {};
  Point(double x, double y) : x(x), y(y) {};
  double x, y;
};

class NearestNeighbors {
 public:
  NearestNeighbors() {};
  std::vector points;
  std::vector nearest(Point, int k);
};
------------------
"""
# 将头文件include 进来
cppyy.include("nearest_neighbors.h")
# 现在已经可以使用 Point 和 NearestNeighbors 类了
Point = cppyy.gbl.Point
KNN = cppyy.gbl.NearestNeighbors
# 构造一个 Point
p = Point(1.0, 2.0)
print(repr(p))

# 我们希望print(p) 可以看到具体的信息
Point.__repr__ = lambda self: "".format(id(self), self.x, self.y)
# 再次print(p)
print(repr(p))  # >> p   # in ipython

# 现在初始化 KNN,需要一系列的Points
from random import random
points = [Point(random()*10, random()*10) for _ in range(10)]
knn = KNN()
knn.points = Vector[Point](points)
list(knn.points)
[,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
 ]
p = Point(2.4, 3.5)
# 现在可以直接调用下面的knn.nearest(p, 2)吗?
# 答案是不行的,因为只include了头文件,knn.nearest函数是未定义的,如果调用将会报错
knn.nearest(p, 2)
-------------------------------------------------
IncrementalExecutor::executeFunction: symbol '?nearest@NearestNeighbors@@QEAA?AV?$vector@VPoint@@V?$allocator@VPoint@@@std@@@std@@VPoint@@H@Z' unresolved while linking symbol '__cf_17'!
You are probably missing the definition of public: class std::vector > __cdecl NearestNeighbors::nearest(class Point,int) __ptr64
Maybe you need to load the corresponding shared library?
    ValueError                                Traceback (most recent call last)
     in 
          1 # 现在可以直接调用下面的knn.nearest(p, 2)吗?
          2 # 答案是不行的,因为只include了头文件,knn.nearest函数是未定义的,如果调用将会报错
    ----> 3 knn.nearest(p, 2)
   
    ValueError: vector NearestNeighbors::nearest(Point, int k) =>
    ValueError: nullptr result where temporary expected
# 需要将包含该函数定义的动态库文件导入进来
# knn_lib.dll 为用MSVC编译的,可能是符号不一致,还是会报错,在linux下导入gcc编译的.so文件以后,是确定可行的
cppyy.load_library("knn_lib.dll")
# 此时应该输出正确的结果
knn.nearest(p, 2)

总结

  • cppyy生成的python 类可以很方便的修改函数实现等
  • 使用cppyy.include 与 cppyy.load_libraries来实现导入c++模块

你可能感兴趣的:(CPPYY include 和 load_libraries及动态特性(二))