From 17a7b6d602ec4e0bf39078a3a9a03ef71d65cf10 Mon Sep 17 00:00:00 2001 From: Bernhard Guillon Date: Tue, 30 Jun 2026 21:02:59 +0200 Subject: Add C hello library with P/Invoke from Baz --- CMakeLists.txt | 1 + baz/Baz.cs | 5 +++++ chello/CMakeLists.txt | 15 +++++++++++++++ chello/hello.c | 5 +++++ 4 files changed, 26 insertions(+) create mode 100644 chello/CMakeLists.txt create mode 100644 chello/hello.c diff --git a/CMakeLists.txt b/CMakeLists.txt index b3973f3..4a9563a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,7 @@ set(RUNTIME_DIR ${DOTNET_ROOT}/shared/Microsoft.NETCore.App/10.0.9) include(cmake/dotnet.cmake) +add_subdirectory(chello) add_subdirectory(baz) add_subdirectory(foobar) add_subdirectory(hello) diff --git a/baz/Baz.cs b/baz/Baz.cs index f3b017f..df4dd96 100644 --- a/baz/Baz.cs +++ b/baz/Baz.cs @@ -1,9 +1,14 @@ using System; +using System.Runtime.InteropServices; public class Baz { + [DllImport("hello_c")] + private static extern void hello_c(); + public static void Print() { Console.WriteLine("Baz"); + hello_c(); } } diff --git a/chello/CMakeLists.txt b/chello/CMakeLists.txt new file mode 100644 index 0000000..f7a276f --- /dev/null +++ b/chello/CMakeLists.txt @@ -0,0 +1,15 @@ +find_program(CMAKE_C_COMPILER NAMES gcc cc) +if(NOT CMAKE_C_COMPILER) + message(FATAL_ERROR "C compiler not found!") +endif() + +set(OUTPUT_FILE ${CMAKE_BINARY_DIR}/libhello_c.so) + +add_custom_command( + OUTPUT ${OUTPUT_FILE} + COMMAND ${CMAKE_C_COMPILER} -shared -fPIC -o ${OUTPUT_FILE} ${CMAKE_CURRENT_SOURCE_DIR}/hello.c + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/hello.c + COMMENT "Compiling hello_c shared library..." +) + +add_custom_target(hello_c ALL DEPENDS ${OUTPUT_FILE}) diff --git a/chello/hello.c b/chello/hello.c new file mode 100644 index 0000000..b99e83d --- /dev/null +++ b/chello/hello.c @@ -0,0 +1,5 @@ +#include + +void hello_c(void) { + printf("hello from c\n"); +} -- cgit v1.2.3