Convert big-endian bytes array to int like struct.unpack in python - python

Recently i'm tring to convert a python serial data analyzer into c++,but i face a problem that how can i convert feff to an integer -2 in c++,and this is a part of my python code.
def Control_Message(input_):
print(input_[4:8])
print(bytes.fromhex(input_[4:8]))
print(struct.unpack('h', bytes.fromhex(input_[4:8])))
print(struct.unpack('h', bytes.fromhex(input_[4:8]))[0])
Angular_Rate_X = struct.unpack('h', bytes.fromhex(input_[0:4]))[0] * 600 * 2 ** -20
and the result is:
feff
b'\xfe\xff'
(-2,)
-2
and now i'm confusing that how can i do the same thing in c++,hope for your help,thanks!

#include <cstdint>
#include <iostream>
int main() {
uint16_t value = 0xfeff;
uint8_t firstByte = static_cast<uint8_t>((value & 0xFF00) >> 8);
uint8_t secondByte = static_cast<uint8_t>(value & 0x00FF);
std::cout << std::hex << static_cast<int>(firstByte) << "\n";
std::cout << std::hex << static_cast<int>(secondByte) << "\n";
}
Output:
fe
ff
If your goal is to get fe and ff separately and then see them as integers, do as follows.
#include <cstdint>
#include <iostream>
int main() {
uint16_t value = 0xfeff;
uint8_t firstByte = static_cast<uint8_t>((value & 0xFF00) >> 8);
uint8_t secondByte = static_cast<uint8_t>(value & 0x00FF);
std::cout << static_cast<int>(firstByte) << "\n";
std::cout << static_cast<int>(secondByte) << "\n";
}
Output:
254
255
If your goal is to find the integer value for feff then do the following
#include <cstdint>
#include <iostream>
int main() {
uint16_t value = 0xfeff;
std::cout << static_cast<int>(value) << "\n";
}
Output:
65279

Related

Reading variable length array in HDF5 C++

I am trying to read an hdf5 file containing variable-length vectors of doubles in C++. I used the following code to create the hdf5 file. It contains one dataset called "test" containing 100 rows of varying lengths. I had to make a couple of changes to the code in the link, so for convenience here is the exact code I used to write the data to hdf5:
#include <iostream>
#include <string>
#include <H5Cpp.h>
#include <vector>
#include <random>
const hsize_t n_dims = 1;
const hsize_t n_rows = 100;
const std::string dataset_name = "test";
int main () {
H5::H5File file("vlen_cpp.hdf5", H5F_ACC_TRUNC);
H5::DataSpace dataspace(n_dims, &n_rows);
// target dtype for the file
auto item_type = H5::PredType::NATIVE_DOUBLE;
auto file_type = H5::VarLenType(&item_type);
// dtype of the generated data
auto mem_type = H5::VarLenType(&item_type);
H5::DataSet dataset = file.createDataSet(dataset_name, file_type, dataspace);
std::vector<std::vector<double>> data;
data.reserve(n_rows);
// this structure stores length of each varlen row and a pointer to
// the actual data
std::vector<hvl_t> varlen_spec(n_rows);
std::mt19937 gen;
std::normal_distribution<double> normal(0.0, 1.0);
std::poisson_distribution<hsize_t> poisson(20);
for (hsize_t idx=0; idx < n_rows; idx++) {
data.emplace_back();
hsize_t size = poisson(gen);
data.at(idx).reserve(size);
varlen_spec.at(idx).len = size;
varlen_spec.at(idx).p = (void*) &data.at(idx).front();
for (hsize_t i = 0; i < size; i++) {
data.at(idx).push_back(normal(gen));
}
}
dataset.write(&varlen_spec.front(), mem_type);
return 0;
}
I am very new to C++ and my issue is trying to read the data back out of this file in C++. I tried to mimic what I would do in Python, but didn't have any luck. In Python, I would do this:
import h5py
import numpy as np
data = h5py.File("vlen_cpp.hdf5", "r")
i = 0 # This is the row I would want to read
arr = data["test"][i] # <-- This is the simplest way.
# Now trying to mimic something closer to C++
did = data["test"].id
dataspace = did.get_space()
dataspace.select_hyperslab(start=(i, ), count=(1, ))
memspace = h5py.h5s.create_simple(dims_tpl=(1, ))
memspace.select_hyperslab(start=(0, ), count=(1, ))
arr = np.zeros((1, ), dtype=object)
did.read(memspace, dataspace, arr)
print(arr) # This gives back the correct data
The python code seems to works fine, so I tried to mimic those steps in C++:
#include <H5Cpp.h>
#include <string>
#include <vector>
#include <stdio.h>
int main(int argc, char **argv) {
std::string filename = argv[1];
// memtype of the file
auto itemType = H5::PredType::NATIVE_DOUBLE;
auto memType = H5::VarLenType(&itemType);
// get dataspace
H5::H5File file(filename, H5F_ACC_RDONLY);
H5::DataSet dataset = file.openDataSet("test");
H5::DataSpace dataspace = dataset.getSpace();
// get the size of the dataset
hsize_t rank;
hsize_t dims[1];
rank = dataspace.getSimpleExtentDims(dims); // rank = 1
std::cout << "Data size: "<< dims[0] << std::endl; // this is the correct number of values
// create memspace
hsize_t memDims[1] = {1};
H5::DataSpace memspace(rank, memDims);
// container to store read data
std::vector<std::vector<double>> data;
// Select hyperslabs
hsize_t dataCount[1] = {1};
hsize_t dataOffset[1] = {0}; // this should be i
hsize_t memCount[1] = {1};
hsize_t memOffset[1] = {0};
dataspace.selectHyperslab(H5S_SELECT_SET, dataCount, dataOffset);
memspace.selectHyperslab(H5S_SELECT_SET, memCount, memOffset);
// vector to store read data
std::vector<double> temp;
temp.reserve(20);
dataset.read(temp.data(), memType, memspace, dataspace);
for (int i = 0; i < temp.size(); i++) {
std::cout << temp[i] << ", ";
}
std::cout << "\n";
return 0;
}
Nothing crashes when I run the C++ program, and the correct number of rows in the "test" dataset is printed (100), but the dataset.read() step isn't working: the first row isn't being read into the vector I want it to be read into (temp). I would greatly appreciate if someone could let me know what I'm doing wrong. Thanks so much.
My goal is to eventually read all 100 rows in the dataset in a loop (placing each row of data into the std:vector temp) and store each one in the std::vectorstd::vector<double> called data. But for now I'm just trying to make sure I can even read the first row.
EDIT: link to hdf5 file
"test" dataset looks like this:
[ 0.16371168 -0.21425339 0.29859526 -0.82794418 0.01021543 1.05546644
-0.546841 1.17456768 0.66068215 -1.04944273 1.48596426 -0.62527598
-2.55912244 -0.82908105 -0.53978052 -0.88870719]
[ 0.33958656 -0.48258915 2.10885699 -0.12130623 -0.2873894 -0.37100313
-1.05934898 -2.3014427 1.45502412 -0.06152739 0.92532768 1.35432642
1.51560926 -0.24327452 1.00886476 0.19749707 0.43894484 0.4394992
-0.12814881]
[ 0.64574273 0.14938582 -0.10369248 1.53727461 0.62404949 1.07824824
1.17066933 1.17196281 -2.05005927 0.13639514 -1.45473056 -1.71462623
-1.11552074 -1.73985207 1.12422121 -1.58694009]
...
EDIT 2:
I've additionally tried without any luck to read the data into (array, armadillo vector, eigen vectorXd). The program does not crash, but what is read into the containers is garbage:
#include <H5Cpp.h>
#include <string>
#include <vector>
#include <stdio.h>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <armadillo>
int main(int argc, char **argv) {
std::string filename = argv[1];
// memtype of the file
auto itemType = H5::PredType::NATIVE_DOUBLE;
auto memType = H5::VarLenType(&itemType);
// get dataspace
H5::H5File file(filename, H5F_ACC_RDONLY);
H5::DataSet dataset = file.openDataSet("test");
H5::DataSpace dataspace = dataset.getSpace();
// get the size of the dataset
hsize_t rank;
hsize_t dims[1];
rank = dataspace.getSimpleExtentDims(dims); // rank = 1
std::cout << "Data size: "<< dims[0] << std::endl; // this is the correct number of values
std::cout << "Data rank: "<< rank << std::endl; // this is the correct rank
// create memspace
hsize_t memDims[1] = {1};
H5::DataSpace memspace(rank, memDims);
// Select hyperslabs
hsize_t dataCount[1] = {1};
hsize_t dataOffset[1] = {0}; // this would be i if reading in a loop
hsize_t memCount[1] = {1};
hsize_t memOffset[1] = {0};
dataspace.selectHyperslab(H5S_SELECT_SET, dataCount, dataOffset);
memspace.selectHyperslab(H5S_SELECT_SET, memCount, memOffset);
// Create storage to hold read data
int i;
int NX = 20;
double data_out[NX];
for (i = 0; i < NX; i++)
data_out[i] = 0;
arma::vec temp(20);
Eigen::VectorXd temp2(20);
// Read data into data_out (array)
dataset.read(data_out, memType, memspace, dataspace);
std::cout << "data_out: " << "\n";
for (i = 0; i < NX; i++)
std::cout << data_out[i] << " ";
std::cout << std::endl;
// Read data into temp (arma vec)
dataset.read(temp.memptr(), memType, memspace, dataspace);
std::cout << "arma vec: " << "\n";
std::cout << temp << std::endl;
// Read data into temp (eigen vec)
dataset.read(temp2.data(), memType, memspace, dataspace);
std::cout << "eigen vec: " << "\n";
std::cout << temp2 << std::endl;
return 0;
}
(ONE) SOLUTION:
After struggling with this a lot, I was able to get a solution working, though admittedly I'm too new to C++ to really understand why this works why and the previous attempts didn't:
#include <H5Cpp.h>
#include <string>
#include <vector>
#include <stdio.h>
int main(int argc, char **argv) {
std::string filename = argv[1];
// Set memtype of the file
auto itemType = H5::PredType::NATIVE_DOUBLE;
auto memType = H5::VarLenType(&itemType);
// Get dataspace
H5::H5File file(filename, H5F_ACC_RDONLY);
H5::DataSet dataset = file.openDataSet("test");
H5::DataSpace dataspace = dataset.getSpace();
// Get the size of the dataset
hsize_t rank;
hsize_t dims[1];
rank = dataspace.getSimpleExtentDims(dims); // rank = 1
std::cout << "Data size: "<< dims[0] << std::endl; // this is the correct number of values
std::cout << "Data rank: "<< rank << std::endl; // this is the correct rank
// Create memspace
hsize_t memDims[1] = {1};
H5::DataSpace memspace(rank, memDims);
// Initialize hyperslabs
hsize_t dataCount[1];
hsize_t dataOffset[1];
hsize_t memCount[1];
hsize_t memOffset[1];
// Create storage to hold read data
hvl_t *rdata = new hvl_t[1];
std::vector<std::vector<double>> dataOut;
for (hsize_t i = 0; i < dims[0]; i++) {
// Select hyperslabs
dataCount[0] = 1;
dataOffset[0] = i;
memCount[0] = 1;
memOffset[0] = 0;
dataspace.selectHyperslab(H5S_SELECT_SET, dataCount, dataOffset);
memspace.selectHyperslab(H5S_SELECT_SET, memCount, memOffset);
// Read out the data
dataset.read(rdata, memType, memspace, dataspace);
double* ptr = (double*)rdata[0].p;
std::vector<double> thisRow;
for (int j = 0; j < rdata[0].len; j++) {
double* val = (double*)&ptr[j];
thisRow.push_back(*val);
}
dataOut.push_back(thisRow);
}
// Confirm data read out properly
for (int i = 0; i < dataOut.size(); i++) {
std::cout << "Row " << i << ":\n";
for (int j = 0; j < dataOut[i].size(); j++) {
std::cout << dataOut[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
If anyone knows a more efficient way that doesn't involve looping over the elements of each row (i.e. pull out an entire row in one go) that would be really helpful, but for now this works fine for me.

Embedded Python in C++ cannot import pandas twice

I'm embedding Python 3.8.2 in C++ code (using Visual Studio 2019). Python has pandasn installed (through pip).
I manage to import pandas from a C++ program, however, when I try to import it a second time, it crashs.
#include <Python.h>
#include <iostream>
int main( int argc, char* argv[] )
{
{
Py_SetPythonHome( L"C:\\Python38" );
// Initialize the Python Interpreter
Py_Initialize();
std::cout << "Importing pandas..." << std::endl;
if ( PyRun_SimpleString( "import pandas" ) == 0 )
std::cout << "SUCCESS" << std::endl;
else
std::cout << "FAIL" << std::endl;
Py_Finalize();
}
{
Py_SetPythonHome( L"C:\\Python38" );
// Initialize the Python Interpreter
Py_Initialize();
std::cout << "Importing pandas..." << std::endl;
if ( PyRun_SimpleString( "import pandas" ) == 0 )
std::cout << "SUCCESS" << std::endl;
else
std::cout << "FAIL" << std::endl;
Py_Finalize();
}
return 0;
}
This crashs with an exception:
_multiarray_umath.cp38-win_amd64.pyd!00007ffbd5b8ca69() Inconnu
_multiarray_umath.cp38-win_amd64.pyd!00007ffbd5b8ffd6() Inconnu
_multiarray_umath.cp38-win_amd64.pyd!00007ffbd5b9d34d() Inconnu
python38.dll!00007ffbd22f6131() Inconnu
python38.dll!00007ffbd22f6092() Inconnu
Output is:
Importing pandas...
SUCCESS
Importing pandas...
Traceback (most recent call last):
File "<string>", line 1, in <module>
Is there any init/uninit step I missed that could make this fail while it shaould work?
Note that I cannot Debug as pandas cannot be loaded in Debug build.
Upon request from OP, I made a small demo for how we wrap user Python scripts in our application to prevent that global variables of user scripts become unintended persistent:
#include <iostream>
#include <string>
#include <Python.h>
const char *PyScript = R"(try:
print(a)
except:
print("a not (yet) defined")
a = 123
print(a)
)";
std::string wrapPyScript(const char* script)
{
std::string source = std::string("def __mainPythonFunction():\n") + script;
{ const char *const indent = "\n ";
for (size_t i = source.size(); i--;) {
size_t n = 1;
switch (source[i]) {
case '\n': if (i && source[i - 1] == '\r') n = 2, --i;
case '\r': source.replace(i, n, indent); break;
}
}
}
source += "\n"
"pass\n"
"\n"
"try:\n"
" __mainPythonFunction()\n"
"except:\n"
" rf.form.appContext.notifyAbort()\n"
" raise\n";
return source;
}
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(Py_Initialize());
std::cout << "\nWithout wrapper:\n\n";
DEBUG(for (int i = 0; i < 2; ++i) {
DEBUG(PyRun_SimpleString(PyScript));
});
std::cout << "\nWith wrapper:\n\n";
DEBUG(for (int i = 0; i < 2; ++i) {
DEBUG(PyRun_SimpleString(wrapPyScript(PyScript).c_str()));
});
std::cout << '\n';
DEBUG(Py_Finalize());
}
Output:
Py_Initialize();
Without wrapper:
for (int i = 0; i < 2; ++i) { DEBUG(PyRun_SimpleString(PyScript)); };
PyRun_SimpleString(PyScript);
a not (yet) defined
123
PyRun_SimpleString(PyScript);
123
123
With wrapper:
for (int i = 0; i < 2; ++i) { DEBUG(PyRun_SimpleString(wrapPyScript(PyScript).c_str())); };
PyRun_SimpleString(wrapPyScript(PyScript).c_str());
a not (yet) defined
123
PyRun_SimpleString(wrapPyScript(PyScript).c_str());
a not (yet) defined
123
Py_Finalize();
However, I'm not quite sure whether this is enough to fix OPs issue with the imported Pandas library.
In our application (where we used the above trick), we import selected libraries once after the Py_Initialize().
(I remember roughly that this was our last desperate resort to fix similar issues like OP observed.)

Vector Values (String and Int) Summation C++

I have moved to C++ from Python, and just wanted to know the way to sum the values that a vector (list) object holds. For example, in python, I could use the code below:
totalSum = 0
myList = [1,2,3,4,5]
for i in myList:
totalSum += i
print(totalSum)
// Output:
15
However, I want to learn the way to do this in C++
totalSum = ""
myList = ["Hello", "World!"]
for i in myList:
totalSum += i
totalSum += " "
print(totalSum)
//Output:
Hello World!
And this one is for the string combination.
Could you please provide how to do this in c++?
I have tried the code below in C++ to test, however, it does not compile successfully:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// A random list/vector here:
vector <double> v = {1, 2, 3, 4, 5};
// Declaring the final string to gather all the vector values:
int sum;
// Iterating through the vector
for (int i = 0; i < v.size(); i++) {
sum += v[i];
}
cout << sum;
return 0;
}
Your code works fine except for the fact you haven't initialized sum variable.
Here is some self-explanatory code discussing what you can use (based on the comments on your question):
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main() {
// For strings:
std::string str;
std::vector<std::string> v = {"Hello", "World!"};
// Method 1: Using range-based for loop:
for (auto &&i : v) {
str += i;
str += " ";
}
std::cout << str << std::endl;
// Method 2: Using std::accumulate():
str = std::accumulate(v.begin(), v.end(), std::string(), [](std::string a, std::string b) {
return std::move(a) + b + " ";
});
std::cout << str << std::endl;
// Method 3: The usual for-loop:
str = "";
for (size_t i = 0; i < v.size(); ++i) {
str += v.at(i); // str += v[i];
str += " ";
}
std::cout << str << std::endl;
// Method 4: Using iterators:
str = "";
for (auto i = v.begin(); i < v.end(); ++i) { // for (auto i = std::begin(v); i < std::end(v); std::advance(i))
str += *i;
str += " ";
}
std::cout << str << std::endl;
// For numbers:
std::vector<int> v2 = {1, 2, 3, 4, 5};
int sum = 0;
// Method 1: Using range-based for loop:
for (auto &&i : v2)
sum += i;
std::cout << sum << std::endl;
// Method 2: Using std::accumulate():
sum = std::accumulate(v2.begin(), v2.end(), 0);
std::cout << sum << std::endl;
// Method 3: The usual for-loop:
sum = 0;
for (size_t i = 0; i < v2.size(); ++i)
sum += v2.at(i); // sum += v2[i]
std::cout << sum << std::endl;
// Method 4: Using iterators:
sum = 0;
for (auto i = v2.begin(); i < v2.end(); ++i) // for (auto i = std::begin(v2); i < std::end(v2); std::advance(i))
sum += *i;
std::cout << sum << std::endl;
return 0;
}
You can replace the argument list of lamda passed to std::accumulate to (auto a, auto b) from (std::string a, std::string b) if you are using C++14 or above.
You need to include <iterator> if you are using std::begin() or std::end() or std::advance(). Also you can remove <numeric> if you are not using std::accumulate().
For documentation of any unfamiliar thing you see in my code, kindly visit https://en.cppreference.com/.
The program has an error. In the for loop, you're trying to compare an integer to an unsigned long long int which is returned by v.size() (use -Wall mode in the compiler arguments to get it).
Using for each syntax, an approach is defined as follows:
#include <iostream>
#include <vector>
int main(void) {
std::vector <std::string> v = {"Hello", "World"};
std::string sum;
for (auto i : v) {
sum += i;
sum += ' ';
}
std::cout << sum << std::endl;
return 0;
}
This will print:
Hello World
If you're interested in the STL algorithms, you can achieve this by using std::accumulate:
#include <vector>
#include <numeric>
#include <string>
#include <iostream>
int main()
{
std::vector <double> v = {1, 2, 3, 4, 5};
std::cout << std::accumulate(v.begin(), v.end(), 0.0) << "\n";
std::vector<std::string> s = {"Hello", "World", "abc", "123"};
std::cout << std::accumulate(s.begin(), s.end(), std::string(),
[](auto& total, auto& str) { return total + str + " "; });
}
Output:
15
Hello World abc 123

SWIG + CMAKE: init function missing

I was provided with a CMAKE-File for a c++ Code and want to wrap its function into python. Whenever I try to import the function it's giving me an Import Error:
dynamic module does not define init function (init_main)
This is the c++ code:
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <Memory/Interface.hpp>
#include <Memory/Subscription.hpp>
using namespace memory::interface;
using namespace memory;
MemoryPtr mMem;
Subscription *s;
std::string write_document;
void subscriber_callback(const Event &event) {
std::cout << "Received an event:" << std::endl;
switch (event.getType()) {
case Event::INSERT:
std::cout << "Insert event with document ID = " << event.getID() << std::endl;
break;
case Event::REMOVE:
std::cout << "Remove event with document ID = " << event.getID() << std::endl;
break;
case Event::QUERY:
std::cout << "Query event with document ID = " << event.getID() << std::endl;
break;
case Event::REPLACE:
std::cout << "Replace event with document ID = " << event.getID() << std::endl;
break;
case Event::ALL:
std::cout << "Generic event with document ID = " << event.getID() << std::endl;
break;
default: std::cout << "Unknown event type." << std::endl;
}
std::cout << "Contained document is: " << event.getDocument() << std::endl;
}
extern "C" int main(int argc, char *argv[]) {
// validate app arguments
if(argc < 3) {
std::cerr << "Usage : " << argv[0] << " <xcf:ShortTerm> <XPATH-trigger>" << std::endl;
return 1;
}
try {
// instantiate the memory interface
mMem = MemoryInterface::getInstance(argv[1]);
std::cout << "Memory interface initialized" << std::endl;
// create the trigger
std::string xpath(argv[2]);
// create a subscriber to a specific xpath event
s = new Subscription(
Condition(Event::INSERT, xpath),
TriggeredAction(boost::bind(&subscriber_callback, _1))
);
mMem->subscribe (*s);
std::cout << "Memory interface subscriber initialized" << std::endl;
// insert command/text to memory
write_document = "<command><stop /></command>";
mMem->insert(write_document);
std::cout << "Written to Memory interface" << std::endl;
// wait for key press
std::string end;
std::cin >> end;
}
catch (const MemoryInterfaceException& e) {
std::cerr << "MemoryInterfaceException: " << e.what() << std::endl;
return 1;
}
catch(std::exception &e) {
std::cerr << std::endl << "Could not initialize memory::interface. Reason:"
<< std::endl << e.what() << std::endl;
return 1;
}
return 0;
}
This is the CMAKE File to which I added the last SWIG part:
cmake_minimum_required(VERSION 3.0.2)
project(xcf_minimal_readwrite)
find_package(PkgConfig)
IF(PKG_CONFIG_FOUND)
message(STATUS "found pkgconfig")
SET(MODULE "Memory")
IF(Memory_FIND_REQUIRED)
SET(Memory_REQUIRED "REQUIRED")
ENDIF()
PKG_CHECK_MODULES(Memory ${Memory_REQUIRED} ${MODULE})
FIND_LIBRARY(Memory_LIBRARY
NAMES ${Memory_LIBRARIES}
HINTS ${Memory_LIBRARY_DIRS}
)
SET(Memory_LIBRARIES ${Memory_LIBRARY})
SET(MODULE "xmltio")
IF(xmltio_FIND_REQUIRED)
SET(xmltio_REQUIRED "REQUIRED")
ENDIF()
PKG_CHECK_MODULES(xmltio ${xmltio_REQUIRED} ${MODULE})
FIND_LIBRARY(xmltio_LIBRARY
NAMES ${xmltio_LIBRARIES}
HINTS ${xmltio_LIBRARY_DIRS}
)
SET(xmltio_LIBRARIES ${xmltio_LIBRARY})
ENDIF()
IF(Memory_FOUND)
message(STATUS "found Memory")
include_directories(${Memory_INCLUDE_DIRS} ${xmltio_INCLUDE_DIRS})
add_executable(${PROJECT_NAME} main.cc)
target_link_libraries(${PROJECT_NAME} ${Memory_LIBRARIES} ${xmltio_LIBRARIES})
install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION bin)
ENDIF()
# This is the part for Python SWIG:
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(main.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(main.i PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(main python main.i main.cc)
SWIG_LINK_LIBRARIES(main ${Memory_LIBRARIES} ${xmltio_LIBRARIES} ${PYTHON_LIBRARIES})
And this is how my main.i looks like:
/* File : main.i */
%module main
%{
/* Put headers and other declarations here */
extern int main(int argc, char *argv[]);
%}
extern int main(int argc, char *argv[]);
Any clue what went wrong here?
Is "main" maybe a bad name for this?
The swig invocation generates a source file that defines the init_main function. This file is either not compiled, or its object file is not linked into the shared object that constitutes your python extension.
Yes, main is a bad name, but here you are stuck at an earlier stage than where this might become a problem.

similar functions like sp.linalg.norm, sp.cross in C++

In python we have library scipy containing sp.linalg.norm, sp.cross. Are there any similar functions in C++ boost library?
There doesn't seem to be.
However, OpenCV has what you need!
L2 norm: http://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#norm
Cross: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#Point_
#include <opencv2/opencv.hpp>
int main(int argc, const char *argv[])
{
cv::Point3d p1(1, 0, 0);
cv::Point3d p2(0, 1, 0);
cv::Point3d cross_prod = p1.cross(p2);
std::cout
<< "<" << cross_prod.x
<< ", " << cross_prod.y
<< ", " << cross_prod.z
<< ">"
<< std::endl;
std::cout << "L2 norm: " << cv::norm(cross_prod) << std::endl;
return 0;
}
The output:
<0, 0, 1>
L2 norm: 1

Categories