← 输入框|github.com|刷新
Skip to content

Need a way to create a structure in LPython, pass a pointer to C #1801

Open

Description

@certik

We need a nice way to create a structure in LPython, and pass a pointer to it into C function that expects void f(struct S *s).

TODO:

  • figure out a nice way to do it
  • add a test
  • make sure it works both in CPython and LPython

Activity

  1. certik commented on May 16, 2023

    @certik
    ContributorAuthor

    I think this page shows how to do that: https://coderslegacy.com/structs-with-python-ctypes/

  2. czgdp1807 commented on May 16, 2023

    @czgdp1807
    Collaborator

    So what you want to do is the following,

    from lpython import i32, f64, ccall, dataclass
    from numpy import empty, int32, float64
    
    @dataclass
    class CompareOperator:
        op_code: i32
        op_name: str
    
    @ccall(header="bindc_06b.h")
    def compare_array_element(value1: i32, value2: f64, op: CPtr) -> i32:
        pass
    
    def test_arrays():
        array1: i32[40] = empty(40, dtype=int32)
        array2: f64[40] = empty(40, dtype=float64)
        compare_operator: CompareOperator = CompareOperator(0, "<")
        compare_op_cptr: CPtr = empty_c_void_p()
        i: i32
    
        for i in range(40):
            array1[i] = i + 1
            array2[i] = float(2*i + 1)
    
        is_small: bool = True
        for i in range(40):
            p_c_pointer(pointer(compare_operator), float_cptr)
            is_small = is_small and bool(compare_array_element(array1[i], array2[i], compare_op_cptr))
    
        print(is_small)
        assert is_small == True
    
    test_arrays()
  3. czgdp1807 commented on May 16, 2023

    @czgdp1807
    Collaborator

    I guess we will have to define the structure in C code as well, correct? Like it will be present as ctypes.Structure in CPython and struct in C code so that both can inter-operate well.

  4. self-assigned this
    on May 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions