This commit is contained in:
blueloveTH 2023-03-13 16:41:28 +08:00
parent 300058b063
commit 234ec85fc6
2 changed files with 16 additions and 16 deletions

View File

@ -223,21 +223,6 @@ struct Pointer{
self.set(vm, args[1]);
return vm->None;
});
vm->bind_method<1>(type, "cast", [](VM* vm, Args& args) {
Pointer& self = CAST(Pointer&, args[0]);
const Str& name = CAST(Str&, args[1]);
int level = 0;
for(int i=name.size()-1; i>=0; i--){
if(name[i] == '*') level++;
else break;
}
if(level == 0) vm->TypeError("expect a pointer type, such as 'int*'");
Str type_s = name.substr(0, name.size()-level);
const TypeInfo* type = _type_db.get(type_s);
if(type == nullptr) vm->TypeError("unknown type: " + type_s.escape(true));
return VAR_T(Pointer, type, level, self.ptr);
});
}
template<typename T>
@ -385,6 +370,21 @@ void add_module_c(VM* vm){
return vm->None;
});
vm->bind_func<2>(mod, "cast", [](VM* vm, Args& args) {
Pointer& self = CAST(Pointer&, args[0]);
const Str& name = CAST(Str&, args[1]);
int level = 0;
for(int i=name.size()-1; i>=0; i--){
if(name[i] == '*') level++;
else break;
}
if(level == 0) vm->TypeError("expect a pointer type, such as 'int*'");
Str type_s = name.substr(0, name.size()-level);
const TypeInfo* type = _type_db.get(type_s);
if(type == nullptr) vm->TypeError("unknown type: " + type_s.escape(true));
return VAR_T(Pointer, type, level, self.ptr);
});
vm->bind_func<1>(mod, "sizeof", [](VM* vm, Args& args) {
const Str& name = CAST(Str&, args[0]);
if(name.find('*') != Str::npos) return VAR(sizeof(void*));

View File

@ -14,7 +14,7 @@ int main(){
pkpy_vm_exec(vm, R"(
from c import *
p = malloc(4).cast("int*")
p = cast(malloc(4), "int*")
ret = f(p)
print(p.get()) # 100
print(ret, ret.get()) # 3.5