I have a bunch (or will have a bunch) of Python code that uses the OpenCV libraries, as well as SimpleCV. I also have a bunch of Haskell code that does some other stuff, but wants to call one function that I define in the Python. This one function returns a three-tuple of doubles.
What's the best way to go about calling this function in Haskell?
For instance, a simplified case is if I have a function in Python
# foo.py
import SimpleCV
def foo():
return (1.0,2.0,3.0)
I want to be able to do this in Haskell
-- bar.hs
main = do
putStrLn $ show pyThingy.foo
I've tried using MissingPy (http://hackage.haskell.org/package/MissingPy), but whenever I try to import the local file I just get
*** Exception: <<MissingPy.Python.Types.PyException>>
Thanks!
You can use Thrift. It's for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.
Related
I have my own C++ library project(with source) written in Qt and it uses QTcpsocket, QUdpSocket, QSerialPort signals and slots.
I would like to support this library in Python as well.
What is the preferred way to do this?
Writing a wrapper in Python, if so does it have obstacles?
Dont know if PyQt is just for this purpose?
Or do you thnink is it better to rewrite the lib in Python by just implementing the logic used in C++ library project.
As this is library is part of a SDK, same applies for supporting QT dll with .NET as well in fact, as a second step after supporting Python.
Example API of Qt.
quint16 SendCommandAsync(CmdBaseSpv1* pcommand,
ConnectionArg connectionArg,
emitLogOptions::emitLogOption logOption,
LogInfo &txLogInfo,
LogInfo &rxLogInfo);
I want to call this function from Python.
Function parameters CmdBaseSpv1, ConnectionArg, emitLogOption, LogInfo are all Qt classes.
Some of these arguments are using the QOBJECT base class.
As you see from the function name; it is an Asynchronous function call. Result will emit a signal so I need to get async result as well.
I'll write down what I know about wrapping C++ libraries and will try to source it, but as a huge disclaimer, I have only used this for something very, very simple myself.
You ask about rewriting the library in Python. I would say this depends. If the code is trivial, then I don't see why not. If it is larger and has to be kept up-to-date with other code (as you imply with .Net), I wouldn't. It makes sense to reuse the same code for both.
My suggestion
From what I see of your code I would try to wrap it using boost::python or SWIG.
How to wrap
The main trouble is going to be to create CmdBaseSpv1, ConnectionArg, etc. in Python.
If you don't need any Qt-classes to instantiate your classes, this should be straightforward. However, in case you need the Qt types inside of Python (e.g. because the constructor of CmdBaseSpv1 requires a QString), your task is a lot more complicated because you need a way to convert a Python-string into a QString. If you can, you should only use stl-types.
Everything in Python
The simplest way to wrap a small C library is to use the cffi module (or ctypes). You can write the full binding in Python. However, this is a lot of manual work if your API is large and can get difficult.
There is another problem: ctypes is only compatible with C, not C++. So you'd need to change your interface to be compatible with C, internally you could still use C++ and Qt.
Wrap by hand
An alternative is to wrap the library calls yourself. You can either do this by using the Python API. There are also a few libraries that help you create the bindings. Boost::python seems especially promising and works with C++.
Binding generators
If your API is very large, you should use a binding generator which parses the C++ code and generates the bindings itself. For example sip is one of them. It is used to create the bindings for the whole Qt library. There are a few binding generators out there, one mentioned in the Python docs is SWIG. PySide uses Shiboken and also has a nice description of it on their website.
SWIG has the additional advantage, that you can create bindings for multiple languages, including C#.
PyQt
PyQt is a binding generated from Qt using sip. You'll probably not need it, unless you need to access the full power of Qt from inside Python. If this is the case, consider using sipfor generating the bindings, so things like the signal-slot mechanism are compatible between your library and PyQt.
Challenges with bindings
Bindings come with a few challenges because Python and C++ are different in some key areas.
Memory-management
Memory management in Python is almost automatic, in C++ you're required to do it manually. For example
def myfunc():
mywidget = QWidget()
at the end of myfunc() mywidget gets garbage collected. In C++ however
void myfunc() {
auto mywidget = new QWidget();
}
mywidget is still around. This means that even when inside Python, you need to take care of the C++ memory management. The problems I've seen are memory leaks and dangling pointers. Watch out for this when using callbacks, you don't want Python to garbage collect the callback while C++ thinks it's still alive.
Exceptions
Not all programming languages have exceptions or deal with them the same way. For example, it would be nice if an exception inside C++ can be caught inside Python.
Links to related question
How to wrap a c++ library for python? (example of boost::python)
Exposing a C++ API to Python (discussion about boost::python, SWIG and more)
https://stackoverflow.com/a/5686873 (discusses Cython, another choice)
Is there a way to run a c++ class from python without using any external libraries like Boost.Python, SWING ect? I don't want to pass any arguments to this class or call a specific method and in my c++ class I have only a void main method, I just want to run the main and that is all.
Or if this is not possible a saw this tutorial http://intermediate-and-advanced-software-carpentry.readthedocs.io/en/latest/c++-wrapping.html#manual-wrapping. But I didn't understand if I should put the hello_wrapper function in the same c++ class where I have the original hello function. And also how can I create a modulo in Python(second part in the tutorial) and where should I put this code
DL_EXPORT(void) inithello(void)
{
Py_InitModule("hello", HelloMethods);
}
Thanks
is there a way to run a c++ class
you don't run C++ classes. They are data types!
Boost.Python, SWING
It's called SWIG, not SWING :)
You can add your own C wrapper code that initializes a PyObject. I'd recommend reading the CPython docs and the examples in the tutorial on extending python. Since you didn't specify a version, I can't give you a discrete link.
Note that python is C, and C++ isn't; which means that you'll have to export several things with a C ABI, i.e. by using external "C" in your code. That might not be something for the uninitiated, and you should certainly evaluate whether not using external wrapper generators is really worth the trouble – especially since using e.g. SWIG properly (which is really a pain) you can get Python objects that really behave like python objects, e.g. you can extend them with python etc.
You know, we can bind every C library on Python or Perl programming languages. A good instance is PyQt; PyQt is bound from Qt.
My question is: Can I do the reverse of the above? I mean: suppose I have a library in Python or Perl, and I want to convert it to a C library...can it be done?
However, you can think to convert a web program to shared library or a set of functions.
My Goal: I want to improve a set of security features.
Yes, you can. The term of art is "embedding," as in "embedded Python" or "embed a Python interpreter." Python has a document about it here: https://docs.python.org/2/extending/embedding.html - the general idea is you must use (at least a small part of) the Python C API to launch Python within a C or C++ application.
Once you realize you can embed a scripting language in C, and that scripting languages can invoke C, you then realize you can also embed one scripting language in another, using C as the bridge between them. For example, RubyLuaBridge: https://bitbucket.org/neomantra/rubyluabridge
A lot of commercial applications embed a scripting language interpreter within a C or C++ host program. A good, well-documented example is Adobe Lightroom, which is roughly half C++ and half Lua. You can read about that from the horse's mouth starting on page xi here: http://www.lua.org/gems/front.pdf
Yes, for python at least: Convert Python program to C/C++ code?.
And for Perl: http://perldoc.perl.org/5.8.9/perlcompile.html.
[EDIT] Per the comment, I'll expand. First, the question "Can I translate Python to C?" has already been answered on SO. See the link.
Second, Perl is actually an interpreted language (just like Python), and has the capability to take that intermediate code and translate it into full blown C for native executables. This is done using the 'B' module and it's other companion modules, such as B::C. There's also a standalone program, 'perlcc' for doing just this. [/EDIT]
Or how can I learn Ruby quickly? Is there a pattern to port a ruby module to python?
I want to add scope system to Sass, but I know little about ruby, and when I started, I found the contents of a module are in several files, there are a lot of variables or classes undefined but referenced.
What's the difference between require keyword and the python's import?
Or at least, is there a ruby IDE that can tell me where is a module, class, variable defined like PyDev does?
There probably are IDE out there that have a bit of code help built in, but I usually don't find I need it. Most Ruby libraries have a certain structural pattern to them. Especially gems by design. You might not notice it at first if you are new to Ruby but once you get the hang of it; things are quite easy to navigate by the naming alone.
To the original intent of your question. I don't think there is an easy way to port a piece of Ruby code like SASS to python in a snap. It would require adequate knowledge of both languages to translate it well. In a way it's kind of like the job of a translator, if you don't know either language well you won't make a lot of sense by what you are producing.
In Ruby require loads a file and executes it. A library will usually have a file named like the library that will include other parts of its components, to make the modules within known.
# req.rb
puts 'Hello World'
# irb
1.9.2p290 :001 > require './req.rb'
Hello World
=> true
So it will basically do the same for you as import in python. You name a module you would like to use and it will work for you after requiring/importing it(given it is known to your load paths).
If you are looking for an equivalent to the python
from <modulename> import *
you should refer to
include <modulename>
Which isn't frowned upon as much in ruby as it is in python.
Hope this answers most of your questions.
Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do that ?
Of course, it's called "extending" in the Python world. The official documentation is here. A short excerpt:
This document describes how to write
modules in C or C++ to extend the
Python interpreter with new modules.
Those modules can define new functions
but also new object types and their
methods. The document also describes
how to embed the Python interpreter in
another application, for use as an
extension language. Finally, it shows
how to compile and link extension
modules so that they can be loaded
dynamically (at run time) into the
interpreter, if the underlying
operating system supports this
feature.
An even easier way for Python would be using the ctypes standard package to run code in DLLs.
Many ways. Generically, this is often called a Foreign Function Interface. That Wikipedia page says the following about Python:
* The major dynamic languages, such as Python, Perl, Tcl, and Ruby,
all provide easy access to native code
written in C/C++ (or any other
language obeying C/C++ calling
conventions).
o Python additionally provides the Ctypes module 2, which
can load C functions from shared
libraries/DLLs on-the-fly and
translate simple data types
automatically between Python and C
semantics. For example:
import ctypes libc = ctypes.CDLL('/lib/libc.so.6' ) # under Linux/Unix
t = libc.time(None) # equivalent C code: t = time(NULL)
print t
A popular choice that supports many languages is SWIG