In Objective-c++, is there a way to move static c functions to another file? - objective-c++

At work, I see lots of ObjC++ files that have dozens of static C helper functions at the top. I'd like to break these static C helper functions out into a separate file and just import the header to ease readability.
Instead of:
static int _AddEm(const int a, const int b) { return a + b }
...
...
...
x 300
Something like:
#import "MyClassHelpers.h"
That would contain all the static C helper functions. The issue is that static seems to only work in the declared file (I'm coming from a Swift and Java background), so I can't just declare a static class in c++ world and bring it and it's helpers over. I'd like to maintain the speed and binary size benefits of using static. What's the best practice for this?
Thanks!

In C, putting static on a function means that the function is restricted to the file where it's declared. (And as a result you can have static functions with the same name in multiple files without conflicting, whereas without static the linker may complain of multiple functions with the same name.) In a way, you can think of it as making the function "private" to the file (in the sense of private members of a class in object-oriented languages you might be familiar with).
If you want to define the code of a function once and use it in multiple files, you want the opposite -- make it not static, and then declare the function signature in the header with extern, like this:
// in MyClassHelpers.h
extern int _AddEm(const int a, const int b);
// in MyClassHelpers.c
int _AddEm(const int a, const int b) { return a + b }
This way, other files that include MyClassHelpers.h can use this function, and the linker will link it with the the single implementation of it compiled from MyClassHelpers.c.
If you had put a static function definition in the header like this:
// in MyClassHelpers.h
static int _AddEm(const int a, const int b) { return a + b }
then each implementation file that includes this header will effectively have its own "private" copy of this function, potentially resulting in the same code being repeated numerous times. (Including a header is basically the same as copy-pasting the contents of the header into the file it is included in, so it is if you wrote this static function definition in every file.)
It occurs to me that perhaps what you're trying to do with these tiny functions is to have calls to them be inlined rather than be called as separate function calls. In that case, perhaps declaring it static and inline in the header will work:
// in MyClassHelpers.h
static inline int _AddEm(const int a, const int b) { return a + b }

Related

PyBind11 Template Class of Many Types

I'd like to use PyBind11 to wrap a specialized array class. However, the array is available in many flavours (one per each plain-old-datatype). The code looks like this:
py::class_<Array2D<float>>(m, "Array2Dfloat", py::buffer_protocol(), py::dynamic_attr())
.def(py::init<>())
.def(py::init<Array2D<float>::xy_t,Array2D<float>::xy_t,float>())
.def("size", &Array2D<float>::size)
.def("width", &Array2D<float>::width)
.def("height", &Array2D<float>::height)
//...
//...
The only way I've thought of to tell PyBind11 about these classes is by duplicating the above for each POD through the use of a very large macro.
Is there a better way to do this?
You can avoid using macros and instead go with a templated declaration function:
template<typename T>
void declare_array(py::module &m, std::string &typestr) {
using Class = Array2D<T>;
std::string pyclass_name = std::string("Array2D") + typestr;
py::class_<Class>(m, pyclass_name.c_str(), py::buffer_protocol(), py::dynamic_attr())
.def(py::init<>())
.def(py::init<Class::xy_t, Class::xy_t, T>())
.def("size", &Class::size)
.def("width", &Class::width)
.def("height", &Class::height);
}
And then call it multiple times:
declare_array<float>(m, "float");
declare_array<int>(m, "int");
...

struct vs class for writing D wrappers around foreign languages

(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 can­not call C++ spe­cial mem­ber func­tions, and vice versa. These in­clude con­struc­tors, de­struc­tors, con­ver­sion op­er­a­tors, op­er­a­tor over­load­ing, and al­lo­ca­tors.
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.

Timer Thread with passed Function* and Param

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.

C# pinvoke marshalling structure containg vector<structure>

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)

shared static function in objective-c iphone?

I need to calculate from pricing based on some business rules and I do not want to duplicate this across several ViewControllers. Coming from a .Net world I would use a static method on a class to do this. What is a similar solution in Objective-C?
A class method most likely - ie. a function in the interface declared with a + at the start.
#implementation PriceCalculator
+ (float)calculatePrice:(float)param1 {
return param1*4.0;
}
#end
(and a similar #interface in a header file)
which is called like so:
price = [PriceCalculator calculatePrice:3.0];
If you don't need to override the behavior in subclasses, you can just write a C function, which is the equivalent of a static method in Java and C#. Otherwise, do as JosephH suggested, and write a class method. Here's his example rewritten as a C function:
float calculatePrice(float amount)
{
return amount * 4.0;
}
The function could be declared/implemented in the .h/.m pair of files for one of your classes if that's convenient, but you could also create a separate .h/.m pair that just contains C functions if you like.