Aug 26, 2024 11:14 AM
(This post was last modified: Nov 15, 2024 01:25 PM by Infinity..)
![[Image: banner-2-tr.gif]](https://i.ibb.co/bFB3CBQ/banner-2-tr.gif)
Hi everyone! Recently, I've been exploring Zig and I have to say, I like it even more than Rust or C. In fact, you can even compile your C programs using Zig!
Note: This isn't an introduction to the programming language—there are better tutorials linked above for that.
In this guide, you'll learn how to create a Zig library and use it in Python or PHP. We'll start with a basic 'Hello, World!' example, and in Part 2 of this series, we'll dive into more complex Windows NT functionality.
First, let's write a simple Zig program that creates a DLL. This DLL will expose a function that either returns a string or performs some computation."
Btw, Zig competes with C instead of depending on it:
https://ziglang.org/learn/overview/#zig-...ding-on-it
Zig site: https://ziglang.org/
Learn zig: https://zig.guide/
Step 1: Create a directory and run
Code
$ zig init-libFollowing things will be generated (note: Ignore shell.nix file, I am on nixos(https://nixos.org/ ) so my Zig installation option differs.
![[Image: twaYdqJ.png]](https://i.imgur.com/twaYdqJ.png)
Our src/main.zig file looks like this
Code
const std = @import("std");
const testing = std.testing;
export fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add func" {
try testing.expect(add(3, 7) == 10);
}Step 2
Build the library
Code
zig build-lib -dynamic -target x86_64-windows-gnu -O ReleaseSmall src/main.zigNow our directory will look something like this
![[Image: PlSdcC0.png]](https://i.imgur.com/PlSdcC0.png)
Now that we have our main.dll lets use it in a python environment
Code
import ctypes
# Load the DLL
mylib = ctypes.CDLL('./main.dll')
# Call the add function
result = mylib.add(5, 3)
print(f"Result of add: {result}")PHP
Code
<?php
// Define the FFI interface
$ffi = FFI::cdef("
int add(int, int);
", "./main.dll");
// Call the add function
$result = $ffi->add(5, 3);
echo "Result of add: $result\n";
?>



![[Image: moonlight_sanctuary.png]](https://moonlight-sanctuary.org/images/moonlight_sanctuary.png)