passing (function) pointers between c and mono - c

Hi after refering to http://www.mono-project.com/Embedding_Mono
i can call methods from managed code by using mono_runtime_invoke.
Now i want to call a method in the managed code with a function pointer (or at least some pointer) as argument from native c code
managed code
public delegate void MyDelegate ();
//method i want to call from native code
public static MyDelegate mono_method(MyDelegate c_ptr)
{
//...do sth
return c_ptr;
}
native code
typedef void (*FUNC_PTR)();
FUNC_PTR my_fct_ptr = some_c_function;
//calling the managed method
MonoObject *result_of_mono_method =
mono_runtime_invoke(mono_method, NULL, my_fct_ptr, NULL);
edit: to point out the problem
how can i call
public static unsafe int* mono_method(int *c_ptr)
from native c code, without using dllImport.

You have several options.
One is to add an internal call that takes a IntPtr (the function pointer) and the arguments: you will then cast the pointer to the function pointer type and call it normally from C code.
Using something like libffi can help to overcome the limitation of having just one function pointer type, it depends how many you need, you didn't specify.
Another option is to use Reflection.Emit to build a dynamic method: in it you will use the calli IL instruction to invoke the function pointer directly.

I'm not exactly sure what you're trying to ask here, but this is the easiest way to do a call back.

Related

Error using unique pointer from interface as attribute of a class

In a nutshell, I need help with the right use of unique_ptr and not with the library ArmNN. So, the next paragraph is just for contextualization.
I am adapting my current application to use the library ArmNN. More specifically, I am doing that through the use of the interface ICaffeParser.
At line 22 of this interface, we have this using definition to define a unique_ptr to the interface, that I believe is the "cause" of my problems.
using ICaffeParserPtr = std::unique_ptr<ICaffeParser, void(*)(ICaffeParser* parser)>;
I am quite sure my problem is the incorrect use of unique_ptr in my context, once I could make some successful tests with a more simple application.
My current code contains a class, let's call it MyClass:
namespace MYNAMESPACE {
class MyClass {
public:
MyClass() {
}
// a lot of functions
// a lot of attributes
private:
// a lot of functions
// a lot of attributes
}
}
In order to make use of the ArmNN library, I have created a new private attribute for MyClass:
armnnCaffeParser::ICaffeParserPtr myParser;
and instantiated myParser at MyClass() constructor:
MyClass::MyClass() {
myParser = armnnCaffeParser::ICaffeParser::Create();
}
Remembering ICaffeParserPtr is a unique_ptr (I think), now I have the following compiling error:
/my_path/src/detector.cpp: In constructor ‘MYNAMESPACE::MyClass::MyClass()’:
/my_path/src/detector.cpp:13:20: error: no matching function for call to ‘std::unique_ptr<armnnCaffeParser::ICaffeParser, void (*)(armnnCaffeParser::ICaffeParser*)>::unique_ptr()’
MyClass::MyClass() {
^
In file included from /usr/aarch64-linux-gnu/include/c++/7/bits/locale_conv.h:41:0,
from /usr/aarch64-linux-gnu/include/c++/7/locale:43,
from /usr/aarch64-linux-gnu/include/c++/7/iomanip:43,
from /usr/include/opencv2/flann/lsh_table.h:40,
from /usr/include/opencv2/flann/lsh_index.h:49,
from /usr/include/opencv2/flann/all_indices.h:42,
from /usr/include/opencv2/flann/flann_base.hpp:43,
from /usr/include/opencv2/flann.hpp:48,
from /usr/include/opencv2/opencv.hpp:62,
from /my_path/src/detector.hpp:11,
from /my_path/src/detector.cpp:1:
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: candidate: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
unique_ptr(auto_ptr<_Up>&& __u) noexcept;
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: template argument deduction/substitution failed:
/my_path/src/detector.cpp:13:20: note: candidate expects 1 argument, 0 provided
MyClass::MyClass() {
^
The error happens because myParser is actually being default-initialized and then assigned on the constructor body of MyClass::MyClass().
Since a function pointer is passed as a custom deleter to std::unique_ptr to form the ICaffeParserPtr type, the default constructor for this particular instance of std::unique_ptr is disabled as per [unique.ptr.single.ctor].
In other words, ICaffeParserPtr, for safety reasons, cannot be default-initialized — which specific function to otherwise assign as its deleter on initialization?
To address this, you should always initialize class members at the member initializer list. In this case, initialize myParser as such:
MyClass::MyClass():
myParser(armnnCaffeParser::ICaffeParser::Create()) {}
This avoids calling the unavailable default constructor for std::unique_ptr, and is generally a better practice than assigning to class members in the constructor body.

Passing a function as a variable and assigning it to an object still able to reference "self" in Lua

So, I'm trying to write a function which accepts functions as its parameters and sets them as 'object' methods in Lua. Is there a specific syntax for this of which I'm not aware?
local function createObjectWithMethods(method1, method2)
local object = {}
object.meth1 = method1
object:meth2 = method2 --this throws an error expecting parameters
return object
end
Is there another way to go about this? I know that I could hardcode a method for the object, but this code needs to have functions passed as parameters, and some of those functions need to be able to reference self. Any ideas?
You need to write the passed-in methods without the automagic self syntax sugar.
That is you can't use:
function obj:meth1(arg1, arg2)
-- code that uses self
end
(unless these functions are defined on some other object and being cross-applied to the new object).
Instead you need to write what the above is sugar for yourself.
function meth1(self, arg1, arg2)
-- code that uses self
end
function meth2(self, arg1, arg2)
-- code that uses self
end
Then you can just call the function normally and assign the functions normally.
local function createObjectWithMethods(method1, method2)
local object = {}
object.meth1 = method1
object.meth2 = method2
return object
end
createObjectWithMethods(meth1, meth2)

Creating New Array with Class Object in GWT

I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.

In php we can access static member functions using class objects. Can someone please tell any practicle use of this feature

In php we can call static member functions using class objects. For example
class Human
{
public static function Speak()
{
echo "I am a human.";
}
}
$human = new Human();
$human->Speak();
What we would expect is that a static member function can only be called using the class name and not the class instance variable (object). But what i have seen while programming is that php allows calling a static member function using the class object also. Is there any practical use or some important reason that this feature has been provided in php ?
This feature exists in java and c++ also. Thanks Oli for pointing this out in your response.
This is the same as in other OO languages, such as C++ and Java. Why would you want the interpreter to prevent this?
UPDATE
My best guess for this (and this is only a guess) is "for convenience". In essence, why should the user of your class necessarily care whether a given member function is static or not? In some circumstances, this will certainly matter; in others, maybe not. I'm not saying this is a great justification, but it's all I can come up with!
it allows you to abstract from the particular definition of the method, so that for example if you had to turn it into a static one at some point, you don't have to rewrite all the method calls!
I can't answer for PHP, (or really for anything) but consider this hypothetical C++:
class base{
public:
static void speak(){cout<<"base\n";}
};
class sub :public base {
public:
static void speak(){cout<<"sub\n"; }
};
int _tmain(int argc, _TCHAR* argv[]){
base *base1 = new base();
base1->speak();
sub *sub1 = new sub();
sub1->speak();
base *sub2 = new sub();
sub2->speak();
((sub*)sub2)->speak();
}
The output would be:
base
sub
base
sub
I'm sure it could be useful... maybe helping you determine which class's static method you should call based on the object currently in hand.

How to get the NPP Instance inside a NPAPI C plugin

I have written a NPAPI plugin in C which needs to call the NPN_Invoke function
(in order to call a JavaScript function).
But NPN_Invoke() takes the NPP instance as a parameter.
Only the NP_New() and NP_Destroy() functions get passed NPP instance. How do I get this NPP instance?
Thanks in advance.
The best way is actually to extend NPObject with a field to save the associated NPP instance, and provide the allocate/deallocate functions with your NPClass definition. You can then cast the NPObject to your subtype to access the actual NPP instance.
I would NOT recommend doing this at a global level (NP_GetEntryPoints, etc.) as suggested above, as there are potentially several instances of your plugin loaded - maybe even on the same page - and you want to be sure you're invoking the correct one. Unfortunately there seems to be a lot of sample code out there where some random instance is just kept in a global variable, and updated as much as possible.
As an example, assuming C++, you'll want to extend NPObject:
struct MyNPObject : public NPObject {
NPP npp_;
explicit MyNPObject(NPP npp) : npp_(npp) {}
};
Then your NPClass definition will need to have allocate and deallocate definitions:
static NPClass obj_Class = {
NP_CLASS_STRUCT_VERSION,
&obj_allocate,
&obj_deallocate,
NULL,
&obj_hasMethod,
&obj_invoke,
...
Which could be implemented like so:
static NPObject* obj_allocate(NPP npp, NPClass *aClass)
{
return new MyNPObject(npp);
}
static void obj_deallocate(NPObject *obj)
{
delete obj;
}
And when you need to call NP_Invoke, assuming you have the NPObject* (inside obj_invoke, for example) you just downcast:
MyNPObject* myObj = reinterpret_cast<MyNPObject*>(obj);
g_browser->invoke(myObj->npp, ...)
In the NP_GetEntryPoints define your own NP_yourNew Function, Now when the after the NP_New the framework calls your NP_yourNew with the instance. The instance could be saved when the your callback just gets invoked.

Resources