我使用 Ruby API 在 C 中創建了 ruby?? 方法,它接收 3 個字串引數:
VALUE cache_class = rb_define_class_under(class, CACHE_CLASS_NAME, rb_cObject);
rb_define_method(cache_class, "cache_test_result", cache_test_result, 3);
在test.rb 中,我呼叫了方法:
Cache.new.cache_test_result("str1", "str2", "str3")
而 C cache_test_result函式的作業方式很奇怪:
VALUE cache_test_result(VALUE str1, VALUE str2, VALUE str3) {
int rstr1_len = RSTRING_LEN(str1) 1;
char buf_str1[rstr1_len];
strlcpy(buf_str1, RSTRING_PTR(str1), rstr1_len);
int rstr2_len = RSTRING_LEN(str2) 1;
char buf_str2[rstr2_len];
strlcpy(buf_str2, RSTRING_PTR(str2), rstr2_len);
int rstr3_len = RSTRING_LEN(str3) 1;
char buf_str3[rstr3_len];
strlcpy(buf_str3, RSTRING_PTR(str3), rstr3_len);
printf("buf_str1: %s\n", buf_str1);
printf("buf_str2: %s\n", buf_str2);
printf("buf_str3: %s\n", buf_str3);
}
此函式的輸出:
buf_str1:
buf_str2: str1
buf_str3: str2
為什么 args 有偏移...?
uj5u.com熱心網友回復:
參考檔案:
C 函式的第一個引數是 self,其余的是方法的引數。
這意味著您需要調整函式原型并添加一個附加引數,例如:
VALUE cache_test_result(VALUE self, VALUE str1, VALUE str2, VALUE str3) {
并且由于型別的 C 物件VALUE可以是任何東西(Ruby 字串、整數或 nil)RSTRING_{PTR,LEN},因此在不確定其 Ruby 型別的情況下,從不使用和類似(宏)函式。相反,您可以使用Check_Type、StringValuePtr或 ,StringValueCStr具體取決于用例。
您的示例可以重寫為:
VALUE cache_test_result(VALUE self, VALUE str1, VALUE str2, VALUE str3) {
// Check if each value is a Ruby string
// (or can be implicitly converted to one) and
// return a pointer to its underlying C string.
// It it also checked if the Ruby string contains NUL.
// If any check fails an exception is raised.
const char *buf_str1 = StringValueCStr(str1);
const char *buf_str2 = StringValueCStr(str2);
const char *buf_str3 = StringValueCStr(str3);
// print each underlying C string
printf("buf_str1: %s\n", buf_str1);
printf("buf_str2: %s\n", buf_str2);
printf("buf_str3: %s\n", buf_str3);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393259.html
上一篇:無法理解C中的字串宣告
