1 The `ffi.string()` function correctly handles array cdata objects returned from C library functions like `strcpy()` and `memcpy()`. 2 3 strcpy() with char[] buffer argument. 4 -- Testcase -- 5 {% 6 import * as ffi from 'ffi'; 7 8 let libc = ffi.dlopen(null); 9 let strcpy = libc.wrap('char *strcpy(char *, const char *)'); 10 11 let buf = ffi.ctype('char[256]'); 12 let result = strcpy(buf, "hello world"); 13 14 print("result: ", ffi.string(result), "\n"); 15 -- End -- 16 17 -- Expect stdout -- 18 result: hello world 19 -- End -- 20 21 22 memcpy() with char[] buffer arguments. 23 -- Testcase -- 24 {% 25 import * as ffi from 'ffi'; 26 27 let libc = ffi.dlopen(null); 28 let memcpy = libc.wrap('void *memcpy(void *, const void *, size_t)'); 29 30 let src = ffi.ctype('char[256]', "test data"); 31 let dst = ffi.ctype('char[256]'); 32 33 memcpy(dst, src, 9); 34 print("copied: ", ffi.string(dst), "\n"); 35 -- End -- 36 37 -- Expect stdout -- 38 copied: test data 39 -- End -- 40 41 42 strcmp() with multiple char[] buffers. 43 -- Testcase -- 44 {% 45 import * as ffi from 'ffi'; 46 47 let libc = ffi.dlopen(null); 48 let strcmp = libc.wrap('int strcmp(const char *, const char *)'); 49 50 let s1 = ffi.ctype('char[256]', "hello"); 51 let s2 = ffi.ctype('char[256]', "hello"); 52 let s3 = ffi.ctype('char[256]', "world"); 53 54 let r1 = strcmp(s1, s2); 55 let r2 = strcmp(s1, s3); 56 print("strcmp(s1, s2): ", r1 == 0 ? "equal" : "not equal", "\n"); 57 print("strcmp(s1, s3): ", r2 < 0 ? "less" : "greater", "\n"); 58 -- End -- 59 60 -- Expect stdout -- 61 strcmp(s1, s2): equal 62 strcmp(s1, s3): less 63 -- End -- 64 65 66 strncpy() with length parameter. 67 -- Testcase -- 68 {% 69 import * as ffi from 'ffi'; 70 71 let libc = ffi.dlopen(null); 72 let strncpy = libc.wrap('char *strncpy(char *, const char *, size_t)'); 73 74 let buf = ffi.ctype('char[256]'); 75 strncpy(buf, "short", 5); 76 77 print("strncpy result: ", ffi.string(buf), "\n"); 78 -- End -- 79 80 -- Expect stdout -- 81 strncpy result: short 82 -- End -- 83 84 85 strcpy() with empty string. 86 -- Testcase -- 87 {% 88 import * as ffi from 'ffi'; 89 90 let libc = ffi.dlopen(null); 91 let strcpy = libc.wrap('char *strcpy(char *, const char *)'); 92 93 let buf = ffi.ctype('char[256]'); 94 strcpy(buf, ""); 95 96 print("empty string: ", ffi.string(buf), "\n"); 97 -- End -- 98 99 -- Expect stdout -- 100 empty string: 101 -- End -- 102 103 104 sprintf() with array buffer. 105 -- Testcase -- 106 {% 107 import * as ffi from 'ffi'; 108 109 let libc = ffi.dlopen(null); 110 let sprintf = libc.wrap('int sprintf(char *, const char *, ...)'); 111 112 let buf = ffi.ctype('char[256]'); 113 sprintf(buf, "value=%d", 42); 114 115 print("sprintf result: ", ffi.string(buf), "\n"); 116 -- End -- 117 118 -- Expect stdout -- 119 sprintf result: value=42 120 -- End -- 121
This page was automatically generated by LXR 0.3.1. • OpenWrt