Is there an ETA on C/C++ Interop?

Currently, I’m doing this in mojo, and it’s really not pretty. Can we link a .so file somehow, rather than specify it explicitly?

from memory import UnsafePointer

# Call C Lib Function

from sys.ffi import DLHandle
var lib = DLHandle("libabc.so")
var printValueAtAddr = lib.get_function[
    fn (UnsafePointer[Float64], Int64) -> NoneType
]("printValueAtAddr")

## Pass data to C
fn toCPtr[T : CollectionElement](mut list : List[T]) -> UnsafePointer[T]:
    return UnsafePointer[T].address_of(list.data[0])

fn toCString(mut str : String) -> UnsafePointer[Byte]:
    return str.as_bytes().unsafe_ptr()
#include <iostream>

extern "C" {
    void printValueAtAddr(double* ptr, int64_t size) {
        for (int64_t i = 0; i < size; i++) {
            std::cout << ptr[i] << " ";
        }
        std::cout << std::endl;
    }

    void printBytesAtAddr(char* ptr) {
        std::string str = ptr;
        std::cout << str << std::endl;
    }
}

1 Like

You can use “external_call”
And link against a lib in compile)

Links to code examples would be really helpful. I found the terminal snake game example. I’d love to look at more.

1 Like

A great resource for some examples is the kapa.ai bot in the Discord server. It should be able to provide you with a good starting point.