Skip to content

Decoder for primitive types in ctypes module #1276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lostmsu opened this issue Nov 9, 2020 · 1 comment
Open

Decoder for primitive types in ctypes module #1276

lostmsu opened this issue Nov 9, 2020 · 1 comment
Assignees

Comments

@lostmsu
Copy link
Member

lostmsu commented Nov 9, 2020

ctypes is a standard Python module for interacting with fixed size integers. Would be nice to provide C# <-> Python conversions for types in that module.

Relevant: https://stackoverflow.com/questions/63801150/how-do-i-pass-a-ulong-type-argument-to-a-c-sharp-function-from-python

@fractus
Copy link
Contributor

fractus commented Jul 29, 2022

A realted topic is numpy and pandas types (any instance of np.ndarray, and pd.core.arrays.ExtensionArray. I tried the following but it didn't work - it's not even triggered, I guess because it's primitives?

    public class NumpyDecoder : IPyObjectDecoder
    {
        public bool CanDecode(PyType objectType, Type targetType)
        {
            return targetType == typeof(double) && objectType.Name.StartsWith("numpy.float64");
        }

        public bool TryDecode<T>(PyObject pyObj, out T value)
        {
            value = (T)(object)pyObj.GetAttr("item").As<double>();
            return true;
        }
    }
Python.Runtime.PyObjectConversions.RegisterDecoder(NumpyDecoder())
xs = np.array([1.0, 2.0], dtype=np.float64)
lst = List[Double]()
lst.Add(xs[0])        # Fails
lst.Add(xs[0].item()) # Works

This is also reported in #1887

See also https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants