1. 生成dll文件
在visual studio中, project->properties->configuration properties->general->Configuration Type
中选择dll
.
然后build改项目生成dll文件。
注意,如果文件后缀名称是.c
,则使用如下格式:
#include<stdio.h>
#include<malloc.h>
//无参数,无返回类型
__declspec(dllexport) void __stdcall hello()
{
printf("Hello,NEU!\n");
}
如果后缀是cpp
,则使用如下格式:
#include <iostream>
extern "C"{
__declspec(dllexport) bool evaluateImage(const char* resultFilename, const char* referenceFilename, const char* roiFilename, const char* txtFilename, double& score);
}
bool evaluateImage(const char* resultFilename, const char* referenceFilename, const char* roiFilename, const char* txtFilename, double& score)
{
std::cout << resultFilename << " " << referenceFilename <<std::endl;
return false;
}
2. 调用dll文件
import ctypes
from ctypes import *
# 下面两行不能少,否则报错
import os
os.add_dll_directory(r'F:\data\raw_data\Task005_Ski10\new\new\liib_test\x64\Debug')
# 将python字符串转c++格式
def convert2c_strint(py_str):
return create_string_buffer(py_str.encode("UTF-8"))
ll = cdll.LoadLibrary
lib = ll("liib_test.dll")
res = "aaa"
ref = "bbb"
roi = "ccc"
txt = "ddd"
score = 0
ok = lib.evaluateImage(convert2c_strint(res), convert2c_strint(ref), convert2c_strint(roi),
convert2c_strint(txt), score)