我编写了一个扩展模块,它使用C++函数指针来存储函数调用序列.我想使用python的multiprocessing模块在不同的进程中"运行"这些调用序列(没有共享状态,因此没有同步问题).
我需要知道,如果函数指针(不是数据指针)仍然有效,后multiprocessing做它的fork().
C++模块:
#include <list>
#include <boost/assert.hpp>
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <boost/foreach.hpp>
/*
* Some functions to be called
*/
double funcA(double d) { return d; }
double funcB(double d) { return d + 3.14; }
double funcC(double d) { return d - 42.0; }
/*
* My container of function pointers (picklable to allow use with multiprocessing)
*/
typedef double(*func_ptr_t)(double);
struct CallSequence {
CallSequence() {
_seq.push_back(funcA);
_seq.push_back(funcB);
_seq.push_back(funcC);
}
std::list<func_ptr_t> _seq;
}; …Run Code Online (Sandbox Code Playgroud) c++ python function-pointers multiprocessing python-extensions
我正在使用Cython(0.15.2)为Python创建扩展(2.6.5).我创建了一个pxd文件和一个pyx文件.以下是我的pyx文件的内容:
cimport capifuncs
cdef class myArray:
cdef capifuncs.myArray *_my_array
def __cinit__(self, size):
self._my_array = capifuncs.array_new(size)
if (self._my_array is NULL):
raise MemoryError()
def __dealloc__(self):
if self._my_array is not NULL:
capifuncs.array_free(self._my_array)
def __bool__(self):
return not capifuncs.IsEmpty(self._my_array)
##############################
# Array methods #
##############################
cpdef getItem(self, unsigned int pos):
if capifuncs.IsEmpty(self._my_array):
raise IndexError("Array is empty")
#if ():
# raise IndexError("Array bounds exceeded")
return capifuncs.array_get_item(self._my_array, pos)
cpdef setItem(self, unsigned int pos, double val):
if capifuncs.IsEmpty(self._my_array):
raise IndexError("Array is empty")
#if ():
# raise IndexError("Array bounds …Run Code Online (Sandbox Code Playgroud) 我只是想在开始编写扩展之前先创建一个 numpy 数组。这是一个超级简单的程序:
#include <stdio.h>
#include <iostream>
#include "Python.h"
#include "numpy/npy_common.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayobject.h"
int main(int argc, char * argv[])
{
int n = 2;
int nd = 1;
npy_intp size = {1};
PyObject* alpha = PyArray_SimpleNew(nd, &size, NPY_DOUBLE);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序在PyArray_SimpleNew调用时出现段错误,我不明白为什么。我试图遵循之前的一些问题(例如numpy array C api和C array to PyArray)。我究竟做错了什么?
我正在为 python 编写 C 扩展。我暂时只是在尝试,我已经编写了一个 hello world 扩展,如下所示:
#include <Python2.7/Python.h>
static PyObject* helloworld(PyObject* self)
{
return Py_BuildValue("s", "Hello, Python extensions!!");
}
static char helloworld_docs[] = "helloworld( ): Any message you want to put here!!\n";
static PyMethodDef helloworld_funcs[] = {
{"helloworld", (PyCFunction)helloworld, METH_NOARGS, helloworld_docs},
{NULL,NULL,0,NULL}
};
void inithelloworld(void)
{
Py_InitModule3("helloworld", helloworld_funcs,"Extension module example!");
}
Run Code Online (Sandbox Code Playgroud)
从我编写的 setup.py 文件安装它并从命令行安装之后,代码工作得很好
python setup.py install
Run Code Online (Sandbox Code Playgroud)
我想要的是以下内容:
我想使用 C 文件作为 python 扩展模块,而不安装它,也就是说,我想将它用作项目中的另一个 python 文件,而不是在我的 python 模块使用其之前需要安装的文件功能。有什么方法可以做到这一点吗?
我使用.pydC++ 和pybind11. 我想.pyi为我的项目生成一个 Python 接口文件.pyd。
有几个类似的问题涉及该mypy stubgen模块,但是,这个问题会产生一个UnicodeError尝试运行文件stubgen Dummy在哪里Dummy的Dummy.pyd问题:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 2: invalid start byte
另一个项目make-stub-files根本不处理.pyd文件,给出('not a python file'文件,从而出现错误。
是否有任何工具可以让我从源.cpp文件或编译后生成 .pyi 文件.pyd文件生成 .pyi 文件?
该问题已在mypyGitHub 存储库中注册。
我正在尝试构建一个使用ffmpeg库的基于C的Python扩展.由于我必须导入一堆库.我用过CMake.我按照python doc的说明进行操作
使用CMake构建没有任何问题.但是当我导入库时,我得到以下异常.
Fatal Python error: PyThreadState_Get: no current thread
Run Code Online (Sandbox Code Playgroud)
我使用mac与python2.7.14(使用Brew安装).
以下是我的
的CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project(extractor C)
set(CMAKE_C_STANDARD 99)
set(EXECUTABLE_NAME "extractor")
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules)
set(EXTRACTOR_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}")
set(target_dir "bin")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -std=99")
add_library(${EXECUTABLE_NAME} SHARED src/frame_extractor.c)
# add_library(${EXECUTABLE_NAME} SHARED src/dipoza.c)
# add_executable(${EXECUTABLE_NAME} main.c)
include_directories(".")
find_package(FFmpeg REQUIRED)
if (FFMPEG_FOUND)
message("Found FFMPEG/LibAV libraries ${FFMPEG_LIBRARIES}")
include_directories(${FFMPEG_INCLUDE_DIR})
target_link_libraries(${EXECUTABLE_NAME} ${FFMPEG_LIBRARIES})
else (FFMPEG_FOUND)
message("cant find libavcodec, libavformat or libavutil. add them manually!!")
endif (FFMPEG_FOUND)
target_link_libraries(${EXECUTABLE_NAME} ${FFMPEG_LIBRARIES})
target_link_libraries (${EXECUTABLE_NAME} "-lm")
target_link_libraries(${EXECUTABLE_NAME} "-framework CoreServices")
target_link_libraries(${EXECUTABLE_NAME} "-framework CoreFoundation")
target_link_libraries(${EXECUTABLE_NAME} …Run Code Online (Sandbox Code Playgroud) 我正在为 C++ 库编写 Cython 包装器,我想将其作为 Python 包分发。我已经想出了我的包的虚拟版本,如下所示(完整源代码在这里)。
\n\n$ tree\n.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 bogus.pyx\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 inc\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 bogus.hpp\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 setup.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 bogus.cpp\n$\n$ cat inc/bogus.hpp \n#ifndef BOGUS\n#define BOGUS\n\nclass bogus\n{\nprotected:\n int data;\n\npublic:\n bogus();\n int get_double(int value);\n};\n\n#endif\n$\n$ cat src/bogus.cpp \n#include "bogus.hpp"\n\nbogus::bogus() : data(0)\n{\n\n}\n\nint bogus::get_double(int value)\n{\n data = value * 2;\n return data;\n}\n$ cat bogus.pyx \n# distutils: language = c++\n# distutils: sources = src/bogus.cpp\n# cython: c_string_type=str, c_string_encoding=ascii\n\ncdef extern from \'bogus.hpp\':\n cdef cppclass bogus:\n bogus() except +\n int get_double(int value)\n\ncdef class Bogus:\n cdef bogus b\n def get_double(self, …Run Code Online (Sandbox Code Playgroud) 我编写了一个 C 扩展来从专有库访问相机的错误消息。结构是
setup.py
dicamsdk\
|---__init__.py
|---control.py
|---pcoError.c
Run Code Online (Sandbox Code Playgroud)
和setup.py
from setuptools import setup, Extension, find_packages
from dicamsdk.control import __version__
pcoErrorModule = Extension("dicamsdk.pcoError",
sources=["dicamsdk/pcoError.c"],
include_dirs=['C:\Program Files (x86)'
'\Digital Camera Toolbox'
'\Sensicam SDK\include'],
define_macros=[("PCO_ERRT_H_CREATE_OBJECT", None)],
)
setup(
name="pydicamsdk",
platforms=["win-amd64", 'win32'],
license="GNU GPLv3",
ext_modules=[pcoErrorModule],
packages=find_packages(),
version=__version__
)
Run Code Online (Sandbox Code Playgroud)
并control.py打算导入已编译的 C 扩展
from . import pcoError
Run Code Online (Sandbox Code Playgroud)
当我尝试构建(或安装)软件包时,我总是收到错误ImportError: cannot import name 'pcoError'。
它似乎唯一有效的方法是注释掉导入control.py并使用setup.py build_ext --inplace. 只需使用编译后的内容,我就可以构建/安装我的库。
我是否有一个解决方案可以setup.py首先编译我的扩展以实现简单的安装?
我正在为 python 开发 C(++) 扩展。我有一个 C 语言库,我使用 Swig 包装它。不幸的是,我想调试 C 扩展中的一些错误。我的程序大量使用通过串行连接发送的 MsgBuffer 类。所有消息可能包含多个部分。如果我将 MsgPart 添加到 MsgBuffer,那么 msg 应该复制消息,但目前看起来我正在添加引用,因为一旦我修改了该部分,添加修改后的部分,初始部分看起来就像这样也被修改。
所以我想做的是在我的 python 程序中设置一个断点并单步执行调试器。
pin = 12 # Pin 12 on Teensy3.2
pullup = False # No need for enabling pull up resistor.
msg = MsgBuffer(TEENSY_REQ_INPUT_PIN)
part= MsgPart()
part.write_uint32(pin)
msg.add_part(part)
part.write_uint32(1 if pullup else 0)
msg.add_part(part) # I would like to set a breakpoint here in order to see whether it is added as reference or it is copied in the c extension …Run Code Online (Sandbox Code Playgroud) 我有成功运行的代码。其CmakeLists.txt是:
cmake_minimum_required(VERSION 3.15)
project(rotapro3)
set(CMAKE_CXX_STANDARD 14)
add_executable(rotapro3 main.cpp):
我想在这个项目中使用 pybind,并按照说明添加以下行:
add_subdirectory(pybind)
pybind11_add_module(rotapro3 main.cpp)
Run Code Online (Sandbox Code Playgroud)
它成功启动,但我收到错误:
add_executable cannot create target "rotapro3" because another target with
the same name already exists. The existing target is a module library
created in source directory "C:/Users/Alex/Dropbox/rotapro3".
Run Code Online (Sandbox Code Playgroud)
我对 CMake 几乎没有了解。我怎样才能重写这些行以允许我使用add_executable?
更新:
我还有另一个更复杂的情况:
set(SOURCE_FILES
unit_test/geometry/monomer_test.cpp
unit_test/geometry/monomer_test.hpp
unit_test/geometry/polymer_test.cpp
unit_test/geometry/polymer_test.hpp
unit_test/geometry/unit_box_test.cpp
unit_test/geometry/unit_box_test.hpp
unit_test/geometry/rect_shape_3d_test.cpp
unit_test/geometry/rect_shape_3d_test.hpp
src/general/guard.cpp
src/general/guard.hpp
src/general/fmt_enum.hpp
src/general/string_format.cpp
src/general/string_format.hpp
src/geometry/monomer.cpp
src/geometry/monomer.hpp
src/geometry/polymer.cpp
src/geometry/polymer.hpp
src/geometry/unit_box.cpp
src/geometry/unit_box.hpp
src/geometry/rect_shape_3d.cpp
src/geometry/rect_shape_3d.hpp
)
include_directories(src/general)
include_directories(src/geometry)
include_directories(unit_test/general)
include_directories(unit_test/geometry)
add_executable(
grapoli_lap ${SOURCE_FILES}
unit_test/general/string_format_test.cpp
unit_test/general/string_format_test.hpp …Run Code Online (Sandbox Code Playgroud) python ×9
c ×4
cmake ×2
packaging ×2
c++ ×1
cpython ×1
cython ×1
mypy ×1
numpy ×1
pybind11 ×1
python-2.7 ×1
python-c-api ×1
setuptools ×1
swig ×1
typeshed ×1