【问题标题】:Passing Arrays to C# DLL from Python Without Unsafe Code and Native C# Arrays [duplicate]在没有不安全代码和本机 C# 数组的情况下从 Python 将数组传递给 C# DLL [重复]
【发布时间】:2017-05-29 14:08:28
【问题描述】:

有谁知道将数组从 Python 传递到 C# DLL 的更好方法,而不必求助于不安全的 C# 代码,最好使用本机 C# 数组?此外,是否有更好或更简洁的方式在 Python 中创建需要传递给 C# DLL 而无需实例化每个元素的数组类型?

我正在从 python 调用一个 C# 库,如下所示:Calling a C# library from python。这是我当前的 C# DLL 代码:

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

namespace TestLib
{
    public class TestLib
    {
        [DllExport("running_sum", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static int running_sum(double* running_sum, int n, double* values)
        {
            // check for errors and return error code
            if (n <= 0 || running_sum == null || values == null)
                return 1;

            running_sum[0] = values[0];
            int i = 1;
            while (i < n)
            {
                running_sum[i] = running_sum[i - 1] + values[i];
                i++;
            }

            // return success
            return 0;
        }
    }
}

这是我调用此 C# DLL 的 Python 3.4 代码:

import ctypes


library = ctypes.cdll.LoadLibrary('../TestLib/TestLib')
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
running_sum_c = ctypes.ARRAY(ctypes.c_double, len(values))()
values_c = ctypes.ARRAY(ctypes.c_double, len(values))()
for i in range(len(values)):
    values_c[i] = values[i]
print('running sum return code: ', library.running_sum(running_sum_c, len(values), values_c))
print('result: ', list(running_sum_c))

【问题讨论】:

标签: c# python arrays python-3.x dll


【解决方案1】:

我认为这是不可能的,最近出现了 CoreRT,它允许编译本机库并在 .Net Framework 之外使用(实际上是 .Net Core)。这真的很酷,而且工作得尽可能好。 (仅适用于windows、linux和osx x64平台)

https://dev.to/encrypt0r/writing-native-libraries-in-c-3kl

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2021-07-18
    • 2013-02-26
    相关资源
    最近更新 更多