Allocating an array of type SWIG C ++ from Python

I am writing a python script for a program that exposed its C ++ API using SWIG. The public SWIG function has the following interface:

void writePixelsRect(JoxColor* colors, int left, int top, int width, int height);

JoxColor is a POD structure that looks like this:

struct JoxColor {
    float r, g, b, a;
};

I can easily create one JoxColor in Python and call the writePixelsRect call like this:

c = JoxApi.JoxColor()
c.r = r
c.g = g
c.b = b
c.a = a
JoxApi.writePixelsRect(c, x, y, 1, 1)

The repeated call to writePixelsRect with a 1x1 pixel rectangle is very slow, so I want to create a JoxColor array from python so that I can write large rectangles at the time. Is this possible with SWIG types?

, ++, JoxColor writePixelsRect, . ++, python script ++ , . ctypes python, , - float, ctypes, JoxColor * SWIG, .

+5
2

, , , pure-ctypes? , libary, , writePixelsRect. ++ mangling, , writePixelsRect, extern "C", - , _Z15writePixelsRectP8JoxColoriiii (, ++, ).

Linux :

nm libjox.so | grep writePixel | cut -d " " -f 3

Python :

from ctypes import *

LIBRARY_NAME = 'libjox.so'
c = cdll.LoadLibrary(LIBRARY_NAME)

WIDTH = 20
HEIGHT = 20

class JoxColor(Structure):
    _fields_ = [("r", c_float), ("g", c_float), ("b", c_float), ("a", c_float)]

ColorBlock = JoxColor * (WIDTH * HEIGHT)

data_array = ColorBlock()

color = JoxColor(0, 0, 1, 0)
for i in range(WIDTH * HEIGHT):
    data_array[i] = color

c._Z15writePixelsRectP8JoxColoriiii(data_array, 0, 0, WIDTH, HEIGHT)

, _Z15writePixelsRectP8JoxColoriiii , , . :

#include <stdio.h>

struct JoxColor {
    float r, g, b, a;
};

void writePixelsRect(JoxColor *colors, int left, int top, int width, int height) {
    int p = 0;
    printf("size: %i, %i\n", width, height);
    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            JoxColor color = colors[p];
            printf("pixel: %f, %f, %f, %f\n", color.r, color.g, color.b, color.a);
        }
    }
}

, .

+2

, SWIG

void writePixelsRect(JoxColor* colors, int left, int top, int width, int height);

, colors - JoxColor, . , ( ), , . , , SWIG.

, , , . , ( ), / :

JoxApi.writePixelsRect(c, x, y, 10, 20)

Edit: , SWIG, , . , Python ( ) JoxColor *. SWIG , Python char **: http://www.swig.org/Doc1.3/Python.html#Python_nn59 API Python C , , Python. JoxColor, Python PyList_GetItem . SWO- PyObject, SWIG_ConvertPtr(list_item_py_object, (void**)&joxcolor_ptr, $descriptor(JoxColor *), 0) JoxColor. .

, JoxColor* JoxColor*, JoxColor* colors, .

FYI, SWIG JoxColor *, JoxColor &, JoxColor JoxColor [] , . Python , // ( Python ). http://www.swig.org/Doc1.3/Python.html#Python_nn22

0

All Articles