1

Anyone know of a better way of passing arrays from Python to a C# DLL without having to resort to unsafe C# code, and preferably using native C# arrays? Also, is there a better or cleaner way of creating the array types in Python that needed to be passed to the C# DLL without having to instantiate each element?

I'm calling a C# library from python as shown here: Calling a C# library from python. Here's my current C# DLL code:

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;
        }
    }
}

Here's my Python 3.4 code calling this C# DLL:

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))
Kamil
  • 11
  • 3

1 Answers1

-1

I don't think it would be possible, recently exists CoreRT which allows to compile native libs and use outside of .Net Framework (really .Net Core). It's really cool and works as fine as is possible. (Only for windows, linux and osx x64 platform)

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

Joseph Moreno
  • 61
  • 1
  • 5