我正在尝试运行一个返回包含多个结构的C函数int(现在).
我的C源代码如下:
struct my_struct {
int i;
int j;
} ;
extern "C" struct my_struct struct_test(){
struct my_struct s;
s.i = 2;
s.j = 331;
return s;
}
Run Code Online (Sandbox Code Playgroud)
相应的Makefile是这样的:
CXX=/usr/bin/g++
PYTHON=/usr/bin/ipython3 --colors Linux
CXXFLAGS=-Wall -fPIC -O3 -c
LDFLAGS=-Wall -shared -Wl,-soname,libfoo.so
TARGETS=mylib.so
all: mylib.so test
mylib.so: mylib.cpp
$(CXX) $(CXXFLAGS) -o mylib.o mylib.cpp
$(CXX) $(LDFLAGS) -o mylib.so mylib.o
test: mylib.so
$(PYTHON) ctypes_call_test.py
clean:
rm -f $(TARGETS)
Run Code Online (Sandbox Code Playgroud)
Python脚本在这里:
import ctypes
libname = './mylib.so'
class my_struct(ctypes.Structure):
_fields_ = [
("i", ctypes.c_int),
("j", …Run Code Online (Sandbox Code Playgroud) 考虑这段代码。
type Int = i32;
const MAX_NUMBER: Int = 1_000_000;
fn main() {
let result1 = with_new();
let result2 = with_capacity();
assert_eq!(result1, result2)
}
fn with_new() -> Vec<Int> {
let mut result = Vec::new();
for i in 0..MAX_NUMBER {
result.push(i);
}
result
}
fn with_capacity() -> Vec<Int> {
let mut result = Vec::with_capacity(MAX_NUMBER as usize);
for i in 0..MAX_NUMBER {
result.push(i);
}
result
}
Run Code Online (Sandbox Code Playgroud)
两个函数产生相同的输出。一个用Vec::new,另一个用Vec::with_capacity。对于较小的值MAX_NUMBER(如示例中所示),with_capacity比 慢new。仅对于较大的最终向量长度(例如 1 亿),使用的版本with_capacity与使用 …