Skip to content

Pointer to bind(c) struct does not work in CPython #2134

Open
@certik

Description

@certik

For example in: https://github.com/lcompilers/lpython/pull/2133/files#diff-72df88224d1b2b9b8ec209f998b9bc6411274c70025c78e287347bca0a4847f6R25.

Here is a minimal example:

from lpython import (i32, f32, dataclass, CPtr, Pointer, c_p_pointer, pointer,
        ccallable, empty_c_void_p, f64, ccall, sizeof, i64)

@ccallable
@dataclass
class A:
    x: i32
    y: f32

def f() -> None:
    x: i32
    y: f32
    a1: A = A(3, f32(3.25))
    a2: Pointer[A]
    a2 = pointer(a1)
    print(a2, pointer(a1))
    x = a2.x
    y = a2.y
    assert x == 3
    assert f64(y) == 3.25

f()

This works with LPython, but fails in CPython with:

$ PYTHONPATH=src/runtime/lpython python integration_tests/structs_02b.py 
c_void_p(4346287752) c_void_p(4346287752)
Traceback (most recent call last):
  File "/Users/ondrej/repos/lpython/integration_tests/structs_02b.py", line 22, in <module>
    f()
  File "/Users/ondrej/repos/lpython/integration_tests/structs_02b.py", line 17, in f
    x = a2.x
AttributeError: 'c_void_p' object has no attribute 'x'

The fix there is:

--- a/src/runtime/lpython/lpython.py
+++ b/src/runtime/lpython/lpython.py
@@ -670,10 +670,7 @@ def pointer(x, type_=None):
             return ctypes.cast(ctypes.pointer(ctypes.c_double(x)),
                     ctypes.c_void_p)
         elif is_dataclass(type_):
-            if issubclass(type_, ctypes.Structure):
-                return ctypes.cast(ctypes.pointer(x), ctypes.c_void_p)
-            else:
-                return x
+            return x
         else:
             raise Exception("Type not supported in pointer()")
 

But this makes many other tests fail, things start to fall apart, so this requires further investigation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions