小编sar*_*ema的帖子

Python 3 ctypes调用函数与返回的struct失败并出现segfault

我正在尝试运行一个返回包含多个结构的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)

c python ctypes python-3.x

2
推荐指数
1
解决办法
88
查看次数

对于较小的最终长度,为什么 Vec::with_capacity 比 Vec::new 慢?

考虑这段代码。

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与使用 …

performance memory-management vector rust

2
推荐指数
1
解决办法
1629
查看次数

标签 统计

c ×1

ctypes ×1

memory-management ×1

performance ×1

python ×1

python-3.x ×1

rust ×1

vector ×1