pybind11 conflict with GetModuleFileName



我使用pybind11让python调用现有的C++模块(库(。然而,连接是通过的,在C++库中,调用:GetModuleFileName(Visual Studio(来确定加载模块在C++中运行时的物理路径。但当我通过pybind11从python(Jupyter Notebook(调用库时,会返回python.exe的物理路径。如何配置或更改以确保获得C++库的物理路径?

C++代码如下所示:Lib.h

#pragma once
void run();

Lib.cpp

#include <fstream>
#include <stdexcept>
#include <windows.h>
#include "libloaderapi.h"
#include "Lib.h"
void run()
{
char buf[1024];
::GetModuleFileName(0, buf, sizeof(buf));
std::ofstream of;
of.open("logging.txt");
if (!of.is_open()) {
throw std::runtime_error("Cannot open logging.txt");
}
of << "The loaded module is " << buf << std::endl;
}

pybind11接口代码:Direct.cpp

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Lib.h"
namespace py = pybind11;
// wrap c++ function
void wrapper() {
run();
}
PYBIND11_MODULE(run_app, m) {
// optional module docstring
m.doc() = "pybind11 plugin";
m.def("run", &wrapper, "Run C++ Application");
}

pybind11安装文件:setup.py

#from distutils.core import setup, Extension
#from distutils import sysconfig
from setuptools import setup, Extension
import pybind11
# The following is for GCC compiler only.
#cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
cpp_args = []
sfc_module = Extension(
'run_app',
sources=['Direct.cpp', 
'Lib.cpp'],
include_dirs=[pybind11.get_include(), '.'],
language='c++',
extra_compile_args=cpp_args,
)
setup(
name='run_app',
version='1.0',
description='Python package with RunApp C++ extension (PyBind11)',
ext_modules=[sfc_module],
)

构建:

python setup.py构建

调用此库的python代码:py_run_app.py

import os
import sys
sys.path.append(os.path.realpath('buildlib.win-amd64-3.7'))
from run_app import run
run()

运行后:

python py_run_app.py

在logging.txt中加载的模块是C:。。。。\python.exe

我想看到的是模块的物理位置。

"模块";用Windows的话说,是一个DLL或一个可执行文件,加载后成为进程的一部分。每个模块都有一个模块句柄;按照惯例,特殊句柄NULL表示用于创建进程的可执行文件。

GetModuleFileName需要模块句柄作为第一个参数。您传递0,就会得到带有特殊句柄NULL的模块的名称,即可执行文件。这是意料之中的事。

为了获得DLL的文件名,你需要找出它的句柄是什么。你可以找到当前模块的句柄:

HMODULE handle;
static char local;
bool ok = GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCSTR)&local,
&handle);

local可以是当前模块中的任何函数或静态/外部变量。参考

相关内容

  • 没有找到相关文章

最新更新