Python3.6
如何将指定的数据结构从C#库返回到python程序?
我拥有一些用C#编写的程序的核心,并希望使用Python访问此代码以扩大代码的操作能力。此时,我只是试图确认我可以从python程序中访问C#代码以验证该过程。
我在C#中具有此功能,可以从python调用。
文件;
IOLibrary.cs
[DllExport("readData", CallingConvention = CallingConvention.Cdecl)]
public static List<TrainRecord> readData(string filename, List<string> trainList, bool excludeListOfTrains, DateTime[] dateRange)
和文件;
TrainLibrary.cs包含数据结构
namespace TrainLibrary
{
public class TrainRecord
{
public string trainID;
public string locoID;
public DateTime dateTime;
public GeoLocation location;
public trainOperator trainOperator;
public trainCommodity commodity;
public double kmPost;
public double speed;
public double powerToWeight;
...
trainOperator和trainCommodity是枚举类型,其余的都是自我解释。
访问该函数的python代码为:
import sys
from datetime import datetime
import clr
clr.AddReference( r"<full path>\IOLibrary.dll")
clr.AddReference( r"<full path>\TrainLibrary.dll")
from IOLibrary import FileOperations
#from TrainLibrary import TrainRecord, trainCommodity, trainOperator, GeoLocation
file = 'file_to_read.txt'
excludeTrainList = ["item1","item2","item3"]
dateRange = [datetime(2018, 1, 1), datetime(2018, 2, 1)]
a = FileOperations()
fileOpInstance = FileOperations()
# records needs to be a List<Trainrecords> ?
records = fileOpInstance.readData(file, excludeTrainList, False, dateRange)
print (len(records))
对于返回“ Hello World”的简单示例,此代码运行良好,但是当我运行代码以访问所需的功能时,出现错误:
No method matches given arguments for readData
现在,我确定这与我传递dateRange或返回结果的方式有关。
我尝试添加注释行
from TrainLibrary import TrainRecord, trainCommodity, trainOperator, GeoLocation
在python程序中,但出现此错误:
No module named 'TrainLibrary'
我如何使Python理解C#数据结构?
答案 0 :(得分:0)
我发现必须在TrainLibrary.cs文件中使用指令包括DLLExport来访问数据结构。
TrainLibrary.cs
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
...
然后按名称导入数据结构
Python程序
clr.AddReference( r"<full path>\TrainLibrary.dll")
from TrainLibrary import TrainRecord, trainCommodity, trainOperator, GeoLocation
...