Created
February 22, 2024 13:49
-
-
Save 1000copy/131997dd285097658e18844819a707db to your computer and use it in GitHub Desktop.
hashtest.zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const ustreamer = @cImport({ | |
@cInclude("hash.c"); | |
}); | |
pub fn main() !void { | |
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) | |
std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); | |
// stdout is for the actual output of your application, for example if you | |
// are implementing gzip, then only the compressed bytes should be sent to | |
// stdout, not any debugging messages. | |
const stdout_file = std.io.getStdOut().writer(); | |
var bw = std.io.bufferedWriter(stdout_file); | |
const stdout = bw.writer(); | |
try stdout.print("Run `zig build test` to run the tests.\n", .{}); | |
try bw.flush(); // don't forget to flush! | |
_ = ustreamer.main1(); | |
} | |
test "simple test" { | |
var list = std.ArrayList(i32).init(std.testing.allocator); | |
defer list.deinit(); // try commenting this out and see if zig detects the memory leak! | |
try list.append(42); | |
try std.testing.expectEqual(@as(i32, 42), list.pop()); | |
} | |
test "c1" { | |
// hashtable_t *ht = ht_create(1024); | |
// ht_put(ht, "foo", "bar"); | |
// printf("%s\n", (char*)ht_get(ht, "foo")); | |
var ht = ustreamer.ht_create(1024); | |
// var x: [*c]u8 = "foo"; | |
// var y: [*c]u8 = "bar"; | |
// var ff = "foo"; | |
// var bb = "bar"; | |
// var fp = ff[0..]; | |
// var bp = bb[0..]; | |
// const x: [*c]const u8 = "some c string"; | |
// const y: [*c]const u8 = "some c string"; | |
// const as_ptr: [*:0]const u8 = x; | |
// _ = as_ptr; | |
var x = "foo".*; | |
var y = "bar".*; | |
_ = ustreamer.ht_put(ht, &x, &y); //ff, bb); // fp, bp); //, bb.ptr); //ff, bb); | |
if (ustreamer.ht_get(ht, &x)) |s| { | |
var anyopaque_pointer: *anyopaque = s; | |
// var item_count: usize = 3; | |
var result = @as([*:0]u8, @ptrCast(anyopaque_pointer)); //[0..item_count]; | |
// while(s) | |
std.debug.print("{s}", .{result}); | |
// var us: usize = 3; | |
// try std.testing.expectEqual(std.mem.eql(u8, result, "bar"), true); | |
} | |
} | |
// 从zig传递字符串到c,是比较曲折的,从c返回的字符串转换为zig的,就更加曲折了。 | |
// 就像它描述的一样:Transferring Zig String Literal to C: A Guide | |
// + How do I pass a string to a C function expecting char * | |
// + C code that uses string literals as non-const char * | |
// 相当曲折的过程:https://stackoverflow.com/questions/72607441/how-can-i-pass-a-zig-string-literal-to-c | |
// 想不到这个解决方法是管用的:https://stackoverflow.com/questions/74491882/how-can-i-cast-anyopaque-to-const-u8 | |
// 我的方案比它更进一步,但是确实是借鉴它的做法的 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment