Suppose I have an object. Might be an objective-C object; might be a C++ object. Is there a way to test which it is that won't throw any exceptions?
EDIT: I'm happy to use any construct that works, including templates if they will do the job.
A friend found this on the Cocoa with Love blog. Apparently, the problem is not trivial.
Since you can use templates, you could do something where you create some type of function that takes a generic template argument, and then instantiate your base-class with all the classes you're using from C++ with a macro. If it's not a C++ class, then the function returns false. So for instance:
//...in some header file
template<typename T>
bool is_cplusplus(const T* type) { return false; }
#define IS_CPLUSPLUS_T(class) \
template<> \
inline bool is_cplusplus(const class* type) { return true; }
//...now use the macro to declare all your C++ classes as "true" in the return
//from is_cplusplus()
IS_CPLUSPLUS_T(my_class1)
IS_CPLUSPLUS_T(my_class2)
//...now use in some code in a separate .cpp file or .mm file, etc.
my_class1 a_class;
if (is_cplusplus(&a_class))
{
//do something
}
I'm specifically using pointers here rather than references because it's my understanding that you can instantiate a C++ template with a pointer to an Objective-C object, where-as instantiations with Objective-C objects themselves doesn't work. If this assumption is not correct, then you can make life a little easier by changing from pointers to references.
I think it can be made a lot simpler than that if the type is available statically (as implied by using a template being an option). Objective-C objects will be implicitly convertible to NSObject and/or 'id' - C++ objects will not (without at least custom code per class to add the cast operator).
// by default, consider it to not be Objective-C.
// C++ object, pointer, built-in, or whatever.
template<typename T>
bool isObjectiveC(const T& ptr) {return false;}
// specialise for any Objective-C object
template<>
bool isObjectiveC(const NSObject*& ptr) {return true;}
template<>
bool isObjectiveC(const id& theID) {return true;}
The function prototypes here pass the parameter by const& because I've had issues with templating with Objective-C types as returned by Objective-C messages, and this seems to work where plain NSObject* doesn't.
Related
(note: this is related to Usage preference between a struct and a class in D language but for a more specific use case)
When writing a D interface to, say, C++ code, SWIG and others do something like this:
class A{
private _A*ptr;//defined as extern(C) elsewhere
this(){ptr=_A_new();}//ditto
this(string s){ptr=_A_new(s);} //ditto
~this(){_A_delete(ptr);} //ditto
void fun(){_A_fun(ptr);}
}
Let's assume no inheritance is needed.
My question is: wouldn't it be preferable to use a struct instead of a class for this?
The pros being:
1) efficiency (stack allocation)
2) ease-of-use (no need to write new everywhere, eg: auto a=A(B(1),C(2)) vs auto a=new A(new B(1),new C(2)) )?
The cons being:
require additional field is_own to handle aliasing via postblit.
What would be the best way to do so?
Is there anything else to worry about?
Here's an attempt:
struct A{
private _A*ptr;
bool is_own;//required for postblit
static A opCall(){//cannot write this() for struct
A a;
a.ptr=_A_new();
a.is_own=true;
return a;
}
this(string s){ptr=_A_new(s); is_own=true;}
~this(){if(is_own) _A_delete(ptr);}
void fun(){_A_fun(ptr);}
this(this){//postblit;
//shallow copy: I don't want to call the C++ copy constructor (expensive or unknown semantics)
is_own=false; //to avoid _A_delete(ptr)
}
}
Note the postblit is necessary for cases when calling functions such as:
myfun(A a){}
I suggest that you read this page. The only functions on C++ classes that you can call in D are virtual functions. That means that
D cannot call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators.
And when you declare a C++ class in D, you use an extern(C++) interface. So, your class/struct would look like this
extern(C++) interface A
{
void fun();
}
However, you'd need another extern(C++) function to allocate any objects of type A, since it's C++ code that has to do that as the D code doesn't have access to any of the constructors. You'd also need a way to pass it back to C++ code to be deleted when you're done with it.
Now, if you want to wrap that interface in a type which is going to call the extern(C++) function to construct it and the extern(C++) function to delete it (so that you don't have to worry about doing that manually), then whether you use a class or struct depends entirely on what you're trying to do with it.
A class would be a reference type, which mirrors what the C++ class actually is. So, passing it around would work without you having to do anything special. But if you wanted a guarantee that the wrapped C++ object was freed, you'd have to do so manually, because there's no guarantee that the D class' finalizer would ever be run (and presumably, that's where you'd put the code for calling the C++ function to delete the C++ object). You'd have to either use clear (which will actually be renamed to destroy in the next release of the compiler - dmd 2.060) to destroy the D object (i.e. call its finalizer and handle the destruction of any of its member variables which are value types), or you'd have to call a function on the D object which called the C++ function to delete the C++ object. e.g.
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
class Wrapper
{
public:
this()
{
_a = createA();
}
~this()
{
deleteA(_a);
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = new Wrapper();
//do stuff...
//current
clear(wrapped);
//starting with dmd 2.060
//destroy(wrapped);
}
But that does have the downside that if you don't call clear/destroy, and the garbage collector never collects your wrapper object, deleteA will never be called on the C++ object. That may or may not matter. It depends on whether the C++ object really needs its destructor to be called before the program terminates or whether it can just let its memory return to the OS (without its destructor being called) when the program terminates if the GC never needs to collect the wrapper object.
If you want deterministic destruction, then you need a struct. That means that you'll need to worry about making the struct into a reference type. Otherwise, if it gets copied, when one of them is destroyed, the C++ object will be deleted, and the other struct will point to garbage (which it will then try and delete when it gets destroyed). To solve that, you could use std.typecons.RefCounted. Then you get something like
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
struct Wrapper
{
public:
static Wrapper opCall()
{
Wrapper retval;
retval._a = createA();
return retval;
}
~this()
{
if(_a !is null)
{
deleteA(_a);
_a = null;
}
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = RefCounted!Wrapper();
//do stuff...
}
You could also define the wrapper so that it has the ref-counting logic in it and avoid RefCounted, but that would definitely be more complicated.
Regardless, I would definitely advise against your suggestion of using a bool to mark whether the wrapper owns the C++ object or not, because if the original wrapper object gets destroyed before all of the copies do, then your copies will point to garbage.
Another option if you did want the C++ object's copy constructor to be used (and therefore treat the C++ object as a value type) would be to add an extern(C++) function which took the C++ object and returned a copy of it and then use it in a postblit.
extern(C++) A copyA(A a);
this(this)
{
if(_a !is null)
_a = copyA(a);
}
Hopefully that makes things clear enough.
I have a class method that returns a pointer to an inner data structure (where the data structure is guaranteed to outlive its use in python code). It looks like:
class MyClass {
...
some_structure* get() {
return inner_structure_;
}
private:
some_structure* inner_structure_;
};
I want to wrap this get() method in Boost::Python so that if two different objects of this class return the same pointer, the associated some_structure objects in python compare equal.
Inside the class_<MyClass> definition I've tried wrapping get() with both return_value_policy<reference_existing_object>() and return_inner_reference<>() call policies, but in both cases, calling get() on different python "MyClass" objects returns different some_structure objects even though all point to the same memory address in C++.
How would I get around this? Might there be a hidden property inside the wrapper object that stores the pointer's address, so I can compare those instead?
Figured out a way to do it, although it still feels hackish and that there should be some easier way. But here goes:
1) Define your own methods that compare the pointers.
template <typename T>
bool eq(const T* self, const T* rhs) {
return self == rhs;
}
template <typename T>
bool ne(const T* self, const T* rhs) {
return !eq<T>(self, rhs);
}
2) Manually declare the __eq__ and __ne__ inside the wrapper class to point to those methods:
class_<smth>("smth", no_init)
...
.def("__eq__", &eq<smth>)
.def("__ne__", &ne<smth>);
I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.
I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).
Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.
To try and understand this, I made a quick scratch application, and found the same thing happens there:
class Foo
{
public:
Foo() : value(1) { printf("constructor"); }
void addOne() { ++value; printf("value is %d", value); }
private:
int value;
};
void Bar()
{
Foo foo1; // prints "constructor"
__block Foo foo2; // doesn't print anything
foo1.addOne(); //prints "2"
foo2.addOne(); //prints "1"
}
Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?
As I understand it, your example there isn't using a block as such, but is declaring foo2 as to be used by a block.
This does funny things to the handling of foo2, which you can read more about here.
Hope that helps.
Stumbled upon this old question. This was a bug that's long been fixed. Now __block C++ objects are properly constructed. If referenced in a block and the block is copied, the heap copy is move-constructed from the original, or copy-constructed if it cannot be move-constructed.
I'm working on finishing up my server for my first iPhone application, and I want to implement a simple little feature.
I would like to run a function (perhaps method as well), if another function returns a certain value after a certain waiting period. Fairly simple concept.... right?
Here's my basic foundation.
template <typename T,class TYP>
struct funcpar{
T (*function)(TYP);
TYP parameter;
funcpar(T (*func)(TYP),TYP param);
funcpar& operator=(const funcpar& fp);
};
The goal here is to be able to call funcpar::function(funcpar::parameter) to run the stored function and parameter, and not have to worry about anything else...
When I attempted to use a void* parameter instead of the template, I couldn't copy the memory as an object (because I didn't know what the end object was going to be, or the beginning for that matter) and when I tried multiple timers, every single object's parameter would change to the new parameter passed to the new timer... With the previous struct I have a
question:
Is it possible to make an all-inclusive pointer to this type of object inside a method of a class? Can I templatize a method, and not the whole class? Would it work exactly like a function template?
I have a managing class that holds a vector of these "jobs" and takes care of everything fairly well. I just don't know how to use a templatized function with the struct, or how to utilize templates on a single method in a class..
I'm also utilizing this in my custom simple threadpool, and that's working fairly well, and has the same problems...
I have another question:
Can I possibly store a function with a parameter before it's run? Something like toRun = dontrunmeyet(withThisParameter);? Is my struct even necessary?
Am I going about this whole thing incorrectly?
If this is overly ambiguous, I can set you up with my whole code for context
In order to create a class method that takes a template parameter, yes, it would work almost exactly like a function template. For example:
class A
{
public:
template<typename T>
void my_function(const T& value) { }
};
int main()
{
A test;
test.my_function(5);
return 0;
}
Secondly, for your structure, you can actually turn that into a functor-object that by overloading operator(), lets you call the structure as-if it were a function rather than having to actually call the specific function pointer members inside the structure. For instance, your structure could be re-written to look like this:
#include <iostream>
template <class ReturnType, class ParameterType>
class funcpar
{
private:
ReturnType (*function)(ParameterType);
ParameterType parameter;
public:
funcpar(ReturnType (*func)(ParameterType),ParameterType param):
function(func), parameter(param) {}
funcpar& operator=(const funcpar& fp);
//operator() overloaded to be a function that takes no arguments
//and returns type ReturnType
ReturnType operator() ()
{
return function(parameter);
}
};
int sample_func(int value)
{
return value + 1;
}
int main()
{
funcpar<int, int> test_functor(sample_func, 5);
//you can call any instance of funcpar just like a normal function
std::cout << test_functor() << std::endl;
return 0;
}
BTW, you do need the functor object (or your structure, etc.) in order to bind a dynamic parameter to a function before the function is called in C/C++ ... you can't "store" a parameter with an actual function. Binding a parameter to a function is actually called a closure, and in C/C++, creating a closure requires a structure/class or some type of associated data-structure you can use to bind a function with a specific parameter stored in memory that is used only for a specific instance of that function call.
I'm in need to call an function that return an structure that contains an int and an vector of other structures in C# for a windows ce 6.0 project:
The function is provided by an 3rd party provider (Chinese manufacturer of the pda), and they only delivered me the .h files, the dll and lib.
The function i'm trying to call in C# is defined in the .h file as :
DLLGSMADAPTER ApnInfoData* GetAvailApnList();
the ApnInfoData structure is as follows:
typedef struct ApnInfoData
{
int m_iDefIndex;
ApnInfoArray m_apnList;
}
typedef struct ApnInfo
{
DWORD m_dwAuthType;
TCHAR m_szName[64];
TCHAR m_szTel[32];
TCHAR m_szUser[32];
TCHAR m_szPassword[32];
TCHAR m_szApnName[32];
}*LPAppInfo;
typedef vector<ApnInfo> ApnInfoArray;
the DLLGSMADAPTER is a
#define DLLGSMADAPTER _declspec(dllexport)
My question is how can i pinvoke this function in the .net cf, since it uses the vector class, and i don't know how to marshal this.
This is not possible. P/Invoke is designed to marshal C types only. You have a few options:
Use C++/CLI to build a managed wrapper around your C library and then use it from C#
Write a C wrapper around your C++ types and then P/Invoke the C wrapper
Write a COM wrapper around the C++ types and then generate a com-interop stub.
The most basic C wrapper around this would go something like this:
// creates/loads/whatever your vector<ApnInfo> and casts it to void*, and then returns it through 'handle'
int GetAppInfoHandle(void **handle);
// casts handle back to vector<ApnInfo> and calls .size()
int GetAppInfoLength(void *handle);
// Load into 'result' the data at ((vector<ApnInfo>*)handle)[idx];
void GetAppInfo(void *handle, int idx, ApnInfo *result);
Wrapping a std::vector<your_struct> in C# is possible with just regular P/Invoke Interop, it is complicated though.
The basic idea of instantiating a C++ object from .NET world is to allocate exact size of the C++ object from .NET, then call the constructor which is exported from the C++ DLL to initialize the object, then you will be able to call any of the functions to access that C++ object, if any of the method involves other C++ classes, you will need to wrap them in a C# class as well, for methods with primitive types, you can simply P/Invoke them. If you have only a few methods to call, it would be simple, manual coding won't take long. When you are done with the C++ object, you call the destructor method of the C++ object, which is a export function as well. if it does not have one, then you just need to free your memory from .NET.
Here is an example.
public class SampleClass : IDisposable
{
[DllImport("YourDll.dll", EntryPoint="ConstructorOfYourClass", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]
public extern static void SampleClassConstructor(IntPtr thisObject);
[DllImport("YourDll.dll", EntryPoint="DoSomething", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]
public extern static void DoSomething(IntPtr thisObject);
[DllImport("YourDll.dll", EntryPoint="DoSomethingElse", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.ThisCall)]
public extern static void DoSomething(IntPtr thisObject, int x);
IntPtr ptr;
public SampleClass(int sizeOfYourCppClass)
{
this.ptr = Marshal.AllocHGlobal(sizeOfYourCppClass);
SampleClassConstructor(this.ptr);
}
public void DoSomething()
{
DoSomething(this.ptr);
}
public void DoSomethingElse(int x)
{
DoSomethingElse(this.ptr, x);
}
public void Dispose()
{
Marshal.FreeHGlobal(this.ptr);
}
}
For the detail, please see the below link,
C#/.NET PInvoke Interop SDK
(I am the author of the SDK tool)