c# - 如何将 python 数据结构返回给 C#

标签 c# python-3.x

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

现在,我确定这与我传递日期范围的方式或返回结果的方式有关。

我尝试包括注释掉的行

from TrainLibrary import TrainRecord, trainCommodity, trainOperator, GeoLocation

在 python 程序中,但出现此错误:

No module named 'TrainLibrary'

如何让 Python 理解 C# 数据结构?

最佳答案

我发现我必须在 TrainLibrary.cs 文件中包含 DLLExport using 指令才能访问数据结构。

火车图书馆.cs

using RGiesecke.DllExport;
using System.Runtime.InteropServices;
...

然后按名称导入数据结构

Python程序

clr.AddReference( r"<full path>\TrainLibrary.dll")
from TrainLibrary import TrainRecord, trainCommodity, trainOperator, GeoLocation
...

关于c# - 如何将 python 数据结构返回给 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213153/

相关文章:

c# - DLL 中的 HOOK C# 方法

python - 为什么os.path指的是项目路径而不是文件路径?

python - 如何将列表的一部分传递给不同的变量?

python-3.x - Pyspark 数据帧,基于组在标志之间迭代

python-3.x - Python单元测试找不到模块

c# - 使用 SvcUtil.exe 创建的服务引用托管 .NET 服务时出现问题 : XmlSerializer errors on Wrapped mode

c# - 使用 using 或项目名称调用项目

postgresql - 如何在 Python 中使用正确的子进程 Pclose?

c# - 在 C# WinForms 中设计自定义 TabPage?

c# - 请等待按钮上的加载栏单击未显示