python调用c++动态库

本文介绍了如何生成64位C++动态库并从Python中调用,详细讲解了Python与C++之间的数据类型匹配,包括int、long、float、double参数,字符与字符串参数的处理,以及C分配内存与释放内存的注意事项。同时探讨了Python与C混合编程的效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成C++动态库

生成C++ 动态库需要注意以下几点:

1.编译成64位的dll库

如果64位的python调用32位的dll会报下面的错误:

OSError: [WinError 193] %1 不是有效的 Win32 应用程序。

这种错误的原因基本上都是64为的python调用了32位的动态库。
解决的方法是生成64位的动态库。安装了visual studio可以使用:
在这里插入图片描述
x64的命令行窗口进行编译。编译命令是:

cl /LD hello.cpp

2. C++ 模板

头文件的模板如下:

//dll.h
#ifndef DLL_EXPORT
#define DECLDIR __declspec(dllimport)
#else
#define DECLDIR __declspec(dllexport)
#endif

c++源文件的模板如下:

//hello.cpp
#include "stdio.h"
#include <iostream>
#include <string.h>

#ifdef __cplusplus
extern "C"
{
   
#endif
#define DLL_EXPORT 
#include "dll.h"

using namespace std;

#pragma execution_character_set("utf-8")

DECLDIR void hello(void){
   
	printf("hello world");
	}
DECLDIR int add_int(int a,int b){
   
	return a+b;
}
DECLDIR float add_float(float a,float b){
   
	return a+b;
}
DECLDIR double add_double(double a,double b){
   
	return a+b;
}
DECLDIR char pass_char(char c){
   
	printf("%c\n",char(c));
	return c;
}
DECLDIR wchar_t pass_wchar(wchar_t  wc){
   
	wcout.imbue(locale("chs"));
	wcout<< wc;
	return wc;
}
DECLDIR char* pass_str(char *s){
   
	printf("%s\n",s);
	return strcat(s,"return");
}
DECLDIR wchar_t* pass_wstr(wchar_t*s,wchar_t wc){
   
	wcout<< s;
	wchar_t *p = wcschr(s,wc);
	return p;
	
}

DECLDIR int* get_memory(int n)
{
   
    int *p = new int[n];
	for(int i = 0; i < n; i++)
	{
   
			p[i] = i;
	}
	return p;
}
 
DECLDIR void free_memory(int *p)
{
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值