How to correctly describe a C++ class in Cython?

Viewed 42

I want to use TcpStream's class(written in C++) in Python via Cython wrapper(I also need it for other purposes). But I got a problem - the desired class is split into several files: Stream.cpp and Stream.hpp; TcpStream.cpp and TcpStream.hpp, which included Stream.hpp. How should I implement .pyx and .pxd files?

Stream.hpp:

#ifndef __STREAM_HPP__
#define __STREAM_HPP__

#include <string>

// Input stream interface
class InputStream {
public:
    // Read exactly byteCount bytes into buffer
    virtual void readBytes(char* buffer, size_t byteCount) = 0;
    // Read a bool from this stream
    bool readBool();
    // Read an int from this stream
    int readInt();
    // Read a long long from this stream
    long long readLongLong();
    // Read a float from this stream
    float readFloat();
    // Read a double from this stream
    double readDouble();
    // Read a string from this stream
    std::string readString();
};

// Output stream interface
class OutputStream {
public:
    // Write byte buffer into this stream
    virtual void writeBytes(const char* buffer, size_t byteCount) = 0;
    // Flush this stream
    virtual void flush() = 0;
    // Write a bool into this stream
    void write(bool value);
    // Write an int into this stream
    void write(int value);
    // Write a long long into this stream
    void write(long long value);
    // Write a float into this stream
    void write(float value);
    // Write a double into this stream
    void write(double value);
    // Write a string into this stream
    void write(const std::string& value);
};

#endif

TcpStream.hpp:

#ifndef __TCP_STREAM_HPP__
#define __TCP_STREAM_HPP__

#include "Stream.hpp"

#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <Ws2tcpip.h>
#include <winsock2.h>
typedef int RECV_SEND_T;
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>
typedef int SOCKET;
typedef ssize_t RECV_SEND_T;
#endif

class TcpStream : public InputStream, public OutputStream {
public:
    TcpStream(const std::string& host, int port);
    ~TcpStream();
    void readBytes(char* buffer, size_t byteCount);
    void writeBytes(const char* buffer, size_t byteCount);
    void flush();

private:
    SOCKET sock;
    static const size_t BUFFER_CAPACITY = 8 * 1024;
    char readBuffer[BUFFER_CAPACITY];
    size_t readBufferPos;
    size_t readBufferSize;
    char writeBuffer[BUFFER_CAPACITY];
    size_t writeBufferPos;
    size_t writeBufferSize;
};

#endif
0 Answers
Related