c# - 导入返回列表的 C# 函数到 Python
问题描述
我的目标是从 C# 函数中获取 Python (2.7) 中的字符串列表,该函数返回一个字符串列表。请看下面的代码。
C# 代码使用UnmanagedExports包。我要导入的功能:
using System;
using System.Collections.Generic;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
namespace GetInheritanceLib
{
public class Program
{
[DllExport("GetInheritanceSource", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.BStr, SizeParamIndex = 1)]
public static List<string> GetInheritanceSource([MarshalAs(UnmanagedType.LPWStr)] string path)
{
List<string> inheritedFrom = new List<string>(); //some correct result of unknown length;
return inheritedFrom;
}
}
}
我尝试在 Python 中导入它:
import os
import ctypes
MyDLL = os.getcwd() + "\ConsoleApp3.dll"
my_dll_loaded = ctypes.cdll.LoadLibrary(MyDLL)
get_inheritance_source = my_dll_loaded.GetInheritanceSource
path = "c:\\dev\\py\\proj"
c_path = ctypes.c_char_p(path)
get_inheritance_source.restype = ctypes.POINTER(ctypes.POINTER(ctypes.c_char_p)) # is it a list of strings?
get_inheritance_source.argtypes = [ctypes.c_char_p] # is it a ctring?
res = get_inheritance_source(c_path) # I expect this is a list of strings, but
我得到的错误:
File "C:/.../c_sharp.py", line .., in <module>
res = get_inheritance_source(c_path)
WindowsError: [Error -532462766] Windows Error 0xE0434352
我不确定这段代码是否正确。请帮我把它们放在一起。谢谢你。
解决方案
PyDotNet帮助我解决了这个问题。
我现在使用的 Python 代码:
import os
import dotnet
dotnet.add_assemblies(os.getcwd()) # a folder with DLLs
dotnet.load_assembly('ConsoleApp3')
import ConsoleApp3
from ConsoleApp3 import Program
path = "c:\\dev\\py\\proj"
res = Program.GetInheritanceSource(path)
推荐阅读
- python - 如何平滑这条锯齿状的 numpy 多项式拟合线?
- python - 如何在 Python 中的地址列上应用拆分字符串操作?
- node.js - 如何在单个 cookie 键中存储多个值
- powershell - 使用字数排除/过滤
- python - django-filter 和 ForeignKeys
- javascript - 可重复使用的角度组件具有与前一个相同的数据 - 输入数据列表
- svg - 宽度和高度在 SVG 中不起作用
- python - 海龟半曲线循环
- javascript - Discord js通过broadcastEval发送消息
- html - CSS - 使用绝对位置设置子宽度大于父宽度