之前上家公司一位C++很厉害的同事,用C++给我做了一个27算法的exe界面程序,由于工作需要我想把这个程序改成C#的形式, 然后用C#生成dll,供python调用,下面是方法。
知识点汇总:1.python调用c++ 生成的dll和调用C#生成的dll 方法不一样的。
python调用C#生成的dll 要用到clr库,而python调用c++生成的dll要用到ctypes
本文重点记录了python调用C#生成的dll
同事给的c++源代码如下:
include "stdio.h"
#include
#include
using namespace std;
int Pepskey(int xx1, int xx2, int factor, int offset);
int main( void )
{
int xx1 = 0;
int xx2 = 0;
int factor = 0;
int offset = 0;
int iRes = 0;
cout<<"Please input:"<<endl;
cout<<"xx1:";
cin>>hex>>xx1;
cout<<"xx2:";
cin>>hex>>xx2;
cout<<"factor:";
cin>>hex>>factor;
cout<<"offset:";
cin>>hex>>offset;
iRes = Pepskey(xx1, xx2, factor, offset);
iRes = iRes & 0xffff;
printf("\nVal = %04X\n", iRes);
cin>>xx1;
return 0;
}
int Pepskey(int xx1, int xx2, int factor, int offset)
{
return (xx1*656+xx2)*factor + offset*6+100;
}
经过修改后的C#代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace third_dll
{
public class Program
{
int iRes = 0;
public int Pepskey(int xx1, int xx2, int factor, int offset)
{
return (xx1 * 656 + xx2) * factor + offset*6+100;
}
/*
void Main(string[] args)
{
int xx1 = 0x5123;
int xx2 = 0x6456;
int factor = 0x7456;
int offset = 0x8321;
iRes = Pepskey(xx1, xx2, factor, offset);
iRes = iRes & 0xffff;
Console.WriteLine("--------------");
Console.WriteLine("\nVal = %04X\n", iRes);
// Console.ReadKey();
}*/
}
}
用C#代码生成的dll 名字为“third_dll.dll”,然后将此dll放到和.py同一路径下。
然后用python进行调用时的python代码为:
import clr
import json
#clr.FindAssembly(path1)
client=clr.AddReference('third_dll')
print(client)
from third_dll import *
the=Program()#实例化
xx1=0x1122
xx2=0x2233
factor=0x4455
offset=0x6677
k1 =the.Pepskey(xx1, xx2, factor, offset)
print(k1)
以上主要程序讲解完毕,实际制作当中踩了坑,
坑1:crl库的安装,一定要安装和python对应的版本,例如我的python版本未3.9.7-32位,所以我下载的crl库要为“pythonnet-2.5.2-cp39-cp39-win32.whl”
坑2:要用C#制作dll时,创建项目时一定要选择这个,(之所以花费了很长时间,其原因就这个选择错了)