{"id":37,"date":"2022-02-18T15:22:51","date_gmt":"2022-02-18T15:22:51","guid":{"rendered":"http:\/\/www.pulsars.info\/wordpress\/?p=37"},"modified":"2022-02-18T15:41:31","modified_gmt":"2022-02-18T15:41:31","slug":"combining-c-and-python-dynamic-library","status":"publish","type":"post","link":"http:\/\/www.pulsars.info\/wordpress\/uncategorized\/combining-c-and-python-dynamic-library\/","title":{"rendered":"Combining C++ and Python: dynamic library"},"content":{"rendered":"\n<p>The simplest way to combine the unprecedented graphical potential of Python (matplotlib&nbsp;library) and a speed of numerical calculations of pure C\/C++ languages&nbsp;is to compile the C-code as a dynamic library.<\/p>\n\n\n\n<p>Here I give an example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#include &lt;cmath&gt; \/\/ for modf and cos \n<strong>using<\/strong> <strong>namespace<\/strong> std;\n<strong>extern<\/strong> \"C\" <strong>double<\/strong> value (<strong>double<\/strong>);  \n<strong>double<\/strong> value (<strong>double<\/strong> step) {\n<strong>double<\/strong> res, pos, fractpart, intpart;\n<strong>int<\/strong> n;\nfractpart = <strong>modf<\/strong>(M_PI \/ 2.0 \/ step, &amp;intpart); \/\/ Compute a number of steps for numerical integration\nn = intpart;\nres = 0.0;\n<strong>for<\/strong> ( <strong>int<\/strong> i=0; i &lt; n; i++) {\n        pos = i * step;                 \/\/ Eulear integration method\n        res += step * <strong>cos<\/strong>(pos);\n}\nres += fractpart*step * <strong>cos<\/strong>(M_PI \/ 2.0);\n<strong>return<\/strong> res;  \n}\n<\/pre>\n\n\n\n<p>extern &#8220;C&#8221; is necessary to clarify which functions are visible outside the dynamical library. The python package &#8216;ctype&#8217; was written for pure C-language. Therefore, the class structure is not inherited. The class structure should be duplicated in the Python code.<\/p>\n\n\n\n<p>To compile the dynamical library we use following command (iOS):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">g++ -dynamiclib -flat_namespace test_func.cpp -o test_fucn.so\n<\/pre>\n\n\n\n<p>For Linux the arguments slightly differ:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">g++ -fPIC -shared test_func.cpp -o test_func.so\n<\/pre>\n\n\n\n<p>The Python script has following structure:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>import<\/strong> numpy <strong>as<\/strong> np                           ## library to work with arrays\n<strong>import<\/strong> matplotlib.pyplot <strong>as<\/strong> plt              ## plotting library\n<strong>import<\/strong> ctypes\n<strong>from<\/strong> ctypes <strong>import<\/strong> cdll, c_double\nlib = cdll.LoadLibrary('.\/test_func.so')    ## use our library written in C\ngrid = np.linspace (0.01, 1.0, 50)           ## prepare a grid with stepsizes\nres_list=[]\nlib.value.restype = ctypes.c_double          ## Declare a type of return argument (important)\n<strong>for<\/strong> i <strong>in<\/strong> <strong>range<\/strong> (0, <strong>len<\/strong>(grid)):               ## for each step size we call our function\n        step = c_double(grid[i])\n        res = lib.value(step)\n        res_list.append(res)\nplt.plot(grid, res_list)                        ## plot the resylt of numerical integration\nplt.xlabel('Numerical integration step size')\nplt.ylabel('Result of integration')\nplt.savefig('plot.pdf')\nplt.show()\n<\/pre>\n\n\n\n<p>The only complicated part of the code is how to return values.<\/p>\n\n\n\n<p>If the code works correctly after we call Python scripts, it prepares following figure:<\/p>\n\n\n\n<figure class=\"wp-block-image is-style-default\"><img decoding=\"async\" src=\"http:\/\/ic.pics.livejournal.com\/ignotur\/17729798\/1785\/1785_900.png\" alt=\"\" title=\"\"\/><\/figure>\n\n\n\n<p>When the integration step is tiny (~0.1) we get the right result. If the integration step is large, the result fluctuates a lot.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The simplest way to combine the unprecedented graphical potential of Python (matplotlib&nbsp;library) and a speed of numerical calculations of pure C\/C++ languages&nbsp;is to compile the&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"http:\/\/www.pulsars.info\/wordpress\/uncategorized\/combining-c-and-python-dynamic-library\/\">Continue Reading<span class=\"screen-reader-text\">Combining C++ and Python: dynamic library<\/span><\/a><\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/posts\/37"}],"collection":[{"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/comments?post=37"}],"version-history":[{"count":1,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/posts\/37\/revisions"}],"predecessor-version":[{"id":38,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/posts\/37\/revisions\/38"}],"wp:attachment":[{"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/media?parent=37"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/categories?post=37"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.pulsars.info\/wordpress\/wp-json\/wp\/v2\/tags?post=37"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}