I am trying to use a C++ library named MP4v2 in Swift. It is mostly working in that I can can call some functions, use some classes, etc.
I am having trouble with a particular function that returns a void pointer. It is NULL on failure, or some other value on success. There is a constant defined to check with, but neither that nor checking for nil works.
if file != MP4_INVALID_FILE_HANDLE {
throws /<path_to_project>/main.swift:19:12: Use of unresolved identifier 'MP4_INVALID_FILE_HANDLE', but it is DOES exist (other constants work).
if file != NULL just causes the same problem, and if file != nil never is true, even if the function failed. What am I doing wrong?
Looking at MP4v2 documentation, here is the definition of the macro to check for invalid handle:
#define MP4_INVALID_FILE_HANDLE ((MP4FileHandle)NULL)
The reason it cannot be used in Swift is because it involves a NULL. In fact, if you define something like
#define MY_NULL NULL
in your Objective-C(++) code and try to use it in Swift, Swift will suggest that you use nil instead.
The handle type MP4FileHandle is
typedef void * MP4FileHandle
So, if you are calling a function like
MP4FileHandle aCPPFunction()
You should be able to check the return value as follows in Swift:
let h : MP4FileHandle = aCPPFunction()
if h != nil
{
// The handle is valid and can be given as an argument to
// other library functions.
}
else
{
// The handle is NULL
}
I understand you tried this. It should work, please double-check. If for whatever strange reason this doesn't work for you, there are some other options:
Write a simple helper function in C, C++, Objective-C or
Objective-C++ to check if the handle is valid and return a integer
flag, which should be easily understood by Swift.
Check h.hashValue. If it is 0, then the handle is invalid,
otherwise it is valid. This is a bad undocumented hack, but it has
worked for me. I would stay away from this one.
Related
I have the following code in Lua:
ABC:
test (X)
The test function is implemented in C + +. My problem is this: I need to know what the variable name passed as parameter (in this case X). In C + + only have access to the value of this variable, but I must know her name.
Help please
Functions are not passed variables; they are passed values. Variables are just locations that store values.
When you say X somewhere in your Lua code, that means to get the value from the variable X (note: it's actually more complicated than that, but I won't get into that here).
So when you say test(X), you're saying, "Get the value from the variable X and pass that value as the first parameter to the function test."
What it seems like you want to do is change the contents of X, right? You want to have the test function modify X in some way. Well, you can't really do that directly in Lua. Nor should you.
See, in Lua, you can return values from functions. And you can return multiple values. Even from C++ code, you can return multiple values. So whatever it is you wanted to store in X can just be returned:
X = test(X)
This way, the caller of the function decides what to do with the value, not the function itself. If the caller wants to modify the variable, that's fine. If the caller wants to stick it somewhere else, that's also fine. Your function should not care one way or the other.
Also, this allows the user to do things like test(5). Here, there is no variable; you just pass a value directly. That's one reason why functions cannot modify the "variable" that is passed; because it doesn't have to be a variable. Only values are passed, so the user could simply pass a literal value rather than one stored in a variable.
In short: you can't do it, and you shouldn't want to.
The correct answer is that Lua doesn't really support this, but there is the debug interface. See this question for the solution you're looking for. If you can't get a call to debug to work directly from C++, then wrap your function call with a Lua function that first extracts the debug results and then calls your C++ function.
If what you're after is a string representation of the argument, then you're kind of stuck in lua.
I'm thinking something like in C:
assert( x==y );
Which generates a nice message on failure. In C this is done through macros.
Something like this (untested and probably broken).
#define assert(X) if(!(X)) { printf("ASSERION FAILED: %s\n", #X ); abort(); }
Here #X means the string form of the arguments. In the example above that is "x==y". Note that this is subtly different from a variable name - its just the string used in the parser when expanding the macro.
Unfortunately there's no such corresponding functionality in lua. For my lua testing libraries I end up passing the stringified version as part of the expression, so in lua my code looks something like this:
assert( x==y, "x==y")
There may be ways to make this work as assert("x==y") using some kind of string evaluation and closure mechanism, but it seemed to tricky to be worth doing to me.
EDIT:
While this doesn't appear to be possible in pure lua, there's a patched version that does seem to support macros: http://lua-users.org/wiki/LuaMacros . They even have an example of a nicer assert.
My background experience is C/C++/C#.
I am using a C++ library in an xcode project (to be specific the library is PJSIP). To use the library i have to wire couple of callbacks to my code like this:
SipTest.m
#include < pjsua-lib/pjsua.h >
static void on_reg_state(pjsua_acc_id acc_id)
{
// Do work
}
static void Init()
{
// pjsua_config and psjua_config_default are defined in the header file from pjsip
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate = &on_reg_state;
}
I want to switch this C++ sytnax to Objective C
so I did:
+(void) on_reg_state:(pjsua_acc_id) acc_id
{
// Do work
}
+(void) Init
{
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate = &on_reg_state; // ***** this is causing compile error
// I tried [CLASS NAME on_reg_state] and i get runtime error
}
I tried to search for delegate in Objective C but i could not find an a similar case where the callback is already implemented in C++ and you want to use it with Objective-C syntax.
Thanks
First of all, there's absolutely no need to convert anything at all. It is perfectly fine to call C++ libraries from Objective-C.
Secondly, whats causing the compiler error is that you're trying to stick a method in a place where there should be a function pointer. You can't make a function pointer out of an Objective-C method using the & Operator. Simply keep your on_reg_state() function and use it as you did before, that's how you do callbacks in Apple's C-based frameworks, too (which you'll need as soon as you move beyond what the high-level Objective-C APIs provide).
And thirdly, your + (void)Init method seems a bit strange. I would strongly discourage you to write a method called Init (capitalized). If you intend to write an initializer, it should be - (id)init, i.e. lowercase and returning id. And don't forget to call the designated initializer of its superclass, check its return value, assign it to self, and return it at the end of the init method (see Implementing an Initializer in Apple's documentation if you're not familiar with that). And if your method is not an initializer, use a different name, e.g. - (void)createConfig.
in this case you'd want to use selectors.
+(void) on_reg_state:(pjsua_acc_id) acc_id
{
// Do work
}
+(void) Init
{
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate_selector = #selector(on_reg_state:);
cfg.cb.target = self; //Self here is the class object in your 'Init' method, which is poorly named.
//Use this like [cfg.cb.target performSelector:cfg.cb.on_regstate_selector withObject:...etc]
}
I am exploring the possibility of creating a Clutter binding for the D
language ( http://d-programming-language.org/) and have started by
trying some simple tests using dynamic loading of libclutter. I've run
into a problem that might derive from the GObject inheritance
system, and I'd appreciate any help getting it figured out. Here's the
rundown: using clutter_stage_get_default returns a ClutterActor* which
I can use with the clutter_actor_* methods. But I always get errors or
segfaults when I use the clutter_stage_* or clutter_container_*
methods. Here's my test code: http://pastebin.com/nVrQ69dU
At the clutter_container_add_actor call on line 56, I get the following error:
(<unknown>:11976): Clutter-CRITICAL **: clutter_container_add_actor:
assertion 'CLUTTER_IS_CONTAINER (container)' failed
In example code, I have noticed the CLUTTER_STAGE and
CLUTTER_CONTAINER macros for casting (these obviously are not
available to me), but as far as I could tell, they simply performed
some checks, then did a plain C cast. If this is incorrect, and some
Gobject type magic needs to be done on the stage pointer before
casting, please let me know. Binding and using the
clutter_stage_set_title or clutter_stage_set_color with cast(ClutterStage*)stage resulted in
segmentation faults, presumably the same issue.
EDIT: Here's a stripped down example with no external dependencies (if you're not on Linux, you'll need to replace the dl calls with your OS's equivalents). This code fails with a segfault, which according to GDB and Valgrind, is in clutter_stage_set_title (in /usr/lib/libclutter-glx-1.0.so.0.600.14)
The problem is that you don't declare the C functions as extern(C). Because of that dmd thinks you're calling a D function and uses the wrong calling convention. One way to do this correctly is like this:
alias extern(C) void function(void*, const char*) setTitleFunc;
auto clutter_stage_set_title = getSym!(setTitleFunc)("clutter_stage_set_title");
I'm not sure how to make it work without the alias though. DMD refuses to parse anything with extern(C) in a template parameter:
auto clutter_stage_set_title = getSym!(extern(C) void function(void*, const char*))("clutter_stage_set_title"); //Doesn't work
BTW: Your cstring function is dangerous: It returns a char* indicating that the string can be modified, but this is not always true: If you pass a string literal to toStringz it might not allocate new memory but return the pointer of the original string instead. String literals are in readonly memory, so this could lead to problems.
You could just adjust your function types to match the C Types (const gchar* in C --> const char* in D) and use toStringz directly.
structs in D cannot inherit from each other and casting struct pointers will return null unless there's a intermediate cast to void* (unlike a C cast) I got refuted here
you're better off adding another abstraction layer using handle-wrapping structs and emulating the checks from those macros when casting
but what happens if you do
clutter_container_add_actor(cast(ClutterContainer*)(cast(void*)stage), textbox);
(casting to void* first and then to ClutterContainer*)
OK, I have some C++ code in a header that is declared like this:
void StreamOut(FxStream *stream,const FxChar *name = nil);
and I get: error:
'nil' was not declared in this scope
nil is a pascal thing, correct?
Should I be using NULL?
I thought they were both the same or at least Zero, no?
In C++ you need to use NULL, 0, or in some brand new compilers nullptr. The use of NULL vs. 0 can be a bit of a debate in some circles but IMHO, NULL is the more popular use over 0.
nil does not exist in standard C++. Use NULL instead.
Yes. It's NULL in C and C++, while it's nil in Objective-C.
Each language has its own identifier for no object. In C the standard library, NULL is a typedef of ((void *)0). In C++ the standard library, NULL is a typedef of 0 or 0L.
However IMHO, you should never use 0 in place of NULL, as it helps the readability of the code, just like having constant variables in your code: without using NULL, the value 0 is used for null pointers as well as base index value in loops as well as counts/sizes for empty lists, it makes it harder to know which one is which. Also, it's easier to grep for and such.
0 is the recommended and common style for C++
If you run a search through glibc you'll find this line of code:
#define NULL 0
It's just a standard way (not sure if it was published anywhere) of marking empty pointers. Variable value of 0 is still a value. Pointer pointing to 0 (0x0000... (it's decimal zero)) is actually pointing nowhere. It's just for readability.
int *var1, var2;
var1 = 0;
var2 = 0;
The above two assignments are not the same though they both look the same
just add at the beginning
#define null '\0'
or whatever you want instead of null and stick with what you prefer. The null concept in C++ is just related to a pointer pointing to nothing (0x0)..
Mind that every compiler may have its own definition of null, nil, NULL, whatever.. but in the end it is still 0.
Probably in the source you are looking at there is a
#define nil '\0'
somewhere in a header file..
I saw some comments on why not to use 0. Generally people don't like magic numbers, or numbers with meaning behind them. Give them a name. I would rather see ANSWER_TO_THE_ULTIMATE_QUESTION over 42 in code.
As for nil, I know Obj-C using nil as well. I would hate to think that someone went against the very popular convention (or at least what I remember) of NULL, which I thought was in a standard library header somewhere. I haven't done C++ in awhile though.
I've seen a lot of example c++ code that wraps function calls in a FAILED() function/method/macro.
Could someone explain to me how this works? And if possible does anyone know a c# equivalent?
It generally checks COM function errors. But checking any function that returns a HRESULT is what it's meant for, specifically. FAILED returns a true value if the HRESULT value is negative, which means that the function failed ("error" or "warning" severity). Both S_OK and S_FALSE are >= 0 and so they are not used to convey an error. With "negative" I mean that the high bit is set for HRESULT error codes, i.e., their hexadecimal representation, which can be found in, e.g., winerror.h, begins with an 8, as in 0x8000FFFF.
This page shows the half of the WinError.h include file that defines FAILED(). It's actually just a very simple macro, the entire definition goes like this:
#define FAILED(Status) ((HRESULT)(Status)<0)
And if possible does anyone know a c# equivalent?
You won't actually need that in C#, unless you're using COM objects. Most .NET functions either already return a (more or less) meaningful value (i.e. null, false) or throw an exception when they fail.
If you're directly accessing a COM object, you can define a simple Failed function that does what the macro in unwind's post does. Define that locally (protected/private), since the messy COM details shouldn't be visible in your app anyway.
In case you didn't know, there's also a SUCCEEDED macro in COM. No need to test for failure :)