首页 > 解决方案 > 从 Python 调用具有默认参数的 C++ 函数

问题描述

我从 DLL 中导出了这个简单的函数(我在 MSVC2015、Windows 10、x64 中工作):

// Main.h
#define DLL_SEMANTICS __declspec (dllexport)
extern "C"
{
    DLL_SEMANTICS int CheckVal(const int x, const int y = 1);

}

代码:

// Main.cpp

    int CheckVal(const int x, const int y)
    { cout << y << endl; return 0; }

}

根据这个SO 线程,使用extern "C"应该不是问题,实际上当从 exe 文件调用这个函数时,我得到了想要的结果(即控制台的“1”)但是当我从 Python 调用它时使用:

import ctypes
from ctypes import cdll

dllPath = r"C:\MyDll.dll"
lib = cdll.LoadLibrary(dllPath)
lib.CheckVal(ctypes.c_int(1))

我正在打印一些垃圾值(通过 PTVS 调试确认这y确实是垃圾值。)

我做错了什么或默认参数不能在 Python 中工作吗?

标签: pythonc++

解决方案


默认参数是 C++ 的一个优点。如果您在 C++ 外部调用,则需要传递两个参数。


推荐阅读