I am working on a project in iOS using Xcode. I want to include a library written in C. But I don't know how to use C library in Objective-C.
Here is the link of Library: https://github.com/bcl/aisparser
Can someone help me?
You're going to hit one obstacle in the form of what's called "name mangling". C++ stores function names in a way not compatible with Obj-C.
Objective-C doesn't implement classes in the same way as C++, so it's not going to like it.
One way around this is to implement a set of simple C functions which call the C++ functions. It'll be a good challenge to keep the number of C functions as low as possible! You'll end up with a nice compact interface! :)
To declare these functions in a C++ file, you'll need to mark them as C with:
extern "C" int function_name(char *blob,int number, double foo) {...}
This disables the standard name-mangling.
Build a header file with the prototypes for all these functions that you can share with your objective C code.
You won't be able to pass classes around in the same way (because your ObjC code can't use them), but you'll be able to pass pointers (although you might have to lie about the types a little).
Related
I need to write native code to delete a picture from the camera library. I am completely new to Objective C so I get a bit confused by the following lines found in Codename One developper guide :
Objective-C relies on argument names as part of the
message (method) signature. So -(NSString*)helloWorld:
(NSString*)param
isn’t
the
same
as
-
(NSString*)helloWorld:
(NSString*)iChangedThisName !
Don’t change argument names in the Objective-C native interface!
Does it that public boolean deleteFile(String path) in java has to be written (BOOL)deleteFile: (NSString*) param in my Objective C native code ?
Or does it mean that the parameter names in the interface file (.h) and in the implementation file (.m) have to be identical ?
Thanks a lot to anyone making it clearer in my mind ;-)!
Cheers
I think you have to keep your java argument's name in your Obj-C files. Otherwhise , it wouldn't be recognized as an implementation of NativeInterface.
And it's simple to maintain the interface.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
My eventual goal is the following:
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Note: this is different from LD_PRELOAD which would override malloc during the entire program execution.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
In theory this is possible, but in practice it's too hard to do.
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Modifying symbol table (even if it were possible) would not get you to your desired goal.
All calls from anywhere inside your ELF binary (let's assume foo is in the main executable), resolve to the same PLT import slot malloc#plt. That slot is resolved to glibc malloc on the first call (from anywhere in your program, assuming you are not using LD_BIND_NOW=1 or similar). After that slot has been resolved, any further modification to the symbol table will have no effect.
You didn't say how much control over foo you have.
If you can recompile it, the problem becomes trivial:
#define malloc my_malloc
int foo() {
// same code as before
}
#undef malloc
If you are handed a precompiled foo.o, you are linking it with my_malloc.o, and you want to redirect all calls from inside foo.o from malloc to my_malloc, that's actually quite simple to do at the object level (i.e. before final link).
All you have to do is go through foo.o relocation records, and change the ones that say "put address of external malloc here" to "put address of external my_malloc here".
If foo.o contains additional functions besides foo, it's quite simple to limit the relocation rewrite to just the relocations inside foo.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
Yes, it is not easy, but the functionality can be packaged into a library, so at the end of the day, it can be made practical.
Typemock Isolator++
(https://www.typemock.com/isolatorpp-product-page/isolate-pp/)
This is free-to-use, but closed source solution. The usage example from documentation should be instructive
TEST_F(IsolatorPPTests, IsExpired_YearIs2018_ReturnTrue) {
Product product;
// Prepare a future time construct
tm* fakeTime = new tm();
fakeTime->tm_year = 2018;
// Fake the localtime method
FAKE_GLOBAL(localtime);
// Replace the returned value when the method is called
// with the fake value.
WHEN_CALLED(localtime(_)).Return(fakeTime);
ASSERT_TRUE(product.IsExpired());
}
Other libraries of this kind
Mimick, from Q: Function mocking in C?
cpp-stub, from Q: Creating stub functionality in C++
Elfspy, for C++, but sometimes it's OK to test C code from C++ unittests, from Q: C++ mock framework capable of mocking non-virtual methods and C functions
HippoMocks, from Q: Mocking C functions in MSVC (Visual Studio)
the subprojects in https://github.com/coolxv/cpp-stub/tree/master/other
... there is still more, feel free to append ...
Alternate approaches
ld's --wrap option and linker scripts, https://gitlab.com/hedayat/powerfake
various approaches described in answers for Q: Advice on Mocking System Calls
and in answers to Q: How to mock library calls?
Rewrite code to make it testable
This is easier in other languages than C, but still doable even in C. Structure code into small functions without side-effects that can be unit-tested without resorting to trickery, and so on. I like this blog Modularity. Details. Pick One. about the tradeoffs this brings. Personally, I guturally dislike the "sea of small functions and tons of dependency injection" style of code, but I realize that that's the easiest to work with, all things considered.
Excursion to other languages
What you are asking for is trivial to do in Python, with the unittest.mock.patch, or possibly by just assigning the mock into the original function directly, and undoing that at the end of the test.
In Java, there is Mockito/PowerMock, which can be used to replace static methods for the duration of a test. Static methods in Java approximately correspond to regular functions in C.
In Go, there is Mockey, which works similarly to what needs to be done in C. It has similar limitations in that inlining can break this kind of runtime mocking. I am not sure if in C you can hit the issue that very short methods are unmockable because there is not enough space to inject the redirection code; I think more likely not, if all calls go through the Procedure Linkage Table.
I have realized that many people sometimes use NS_INLINE functions in their code. I am curios how they know when to use it and why they use it.
I have read that INLINE functions have less instructions than objective-C functions. I am a bit lost in this area because I don't know too much about C.
Some example that I've seen are these:
NS_INLINE id NilToEmptyString(id obj)
{
return obj ? : #"";
}
NS_INLINE BOOL isRunningTests(void)
I want to use it at some specific places. For example. I need to get all the assets of the Gallery and then check if they have location and date. I would like to do those functions checkLocation and checkDate as inline functions.
Some users have 5000 pictures, with iPhone 4s the time increases until 5 minutes, that is too much. I want to refactor the code and I read that sometimes inline functions is not a bad way.
NS_INLINE is a macro for the __attribute__((always_inline)) compiler directive, which is stronger than the normal inline keyword. Use it only if you're very sure inlining will result in faster code without unnecessary executable bloat.
Initial Googling indicates that there's no built-in way to do regular expressions in an Objective-C Cocoa application.
So four questions:
Is that really true?
Are you kidding me?
Ok, then is there a nice open-source library you recommend?
What are ways to get close enough without importing a library, perhaps with the NSScanner class?
I noticed that as of iOS 4.0 Apple provides a NSRegularExpression class. Additionally, as of 10.7, the class is available under OS X.
Yes, there's no regex support in Cocoa. If you're only interested in boolean matching, you can use NSPredicate which supports ICU regex syntax. But usually you're interested in the position of the match or position of subexpressions, and you cannot get it with NSPredicate.
As mentioned you can use regex POSIX functions. But they are considered slow, and the regex syntax is limited compared to other solutions (ICU/pcre).
There are many OSS libraries, CocoaDev has an extensive list.
RegExKitLite for example doesn't requires any libraries, just add the .m and .h to your project.
(My complaint against RegExKitLite is that it extends NSString via category, but it can be considered as a feature too. Also it uses the nonpublic ICU libraries shipped with the OS, which isn't recommended by Apple.)
RegexKit is the best I've found yet. Very Cocoa:y. I'm using the "Lite" version in several of our iPhone apps:
sourceforge
lingonikorg
You can use the POSIX Regular Expressions library (Yay for a POSIX compliant OS). Try
man 3 regex
The cheap and dirty hack solution that I use to solve REGEX and JSON parsing issues is to create a UIWebView object and inject Javascript function(s) to do the parsing. The javascript function then returns a string of the value (or list of values) I care about. In fact, you can store a small library set of functions customized for particular tasks and then just call them as needed.
I don't know if it this technique scales to huge volumes of repeated parsing requests, but for quick transactional stuff it gets the job done without depending on any extra external resources or code you might not understand.
I like the AGRegex framework which uses PCRE, handy if you are used to the PCRE syntax. The best version of this framework is the one in the Colloquy IRC client as it has been upgraded to use PCRE 6.7:
http://colloquy.info/project/browser/trunk/Frameworks/AGRegex
It's very lightweight, much more so than RegExKit (although not as capable of course).
NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0.
During my search on this topic I came across CocoaOniguruma which uses Oniguruma, the Regular Expression engine behind Ruby1.9 and PHP5. It seems a bit newer compared to the existing OregKit (in Japanese). Not sure how these stack up against other bindings.
Googling alittle, found this library:
RegexOnNSString
Open source library, containing functions like:
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL)ignoreCase
and using NSRegularExpression class. Quite easy to use and no need to worry about anything.
Please, note that NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0, as Datasmid mentioned.
I make it easy. I add a new C++ file to my Objective C project, rename it as .mm, and then create a standard C++ class inside. Then, I make a static class method in the "public:" section for a C++ function that takes an NSString and returns an NSString (or NSArray, if that's what you want). I then convert NSString to C++ std::string like so:
// If anyone knows a more efficient way, let me know in the comments.
// The "if" condition below is because ObjC crashes if converting to
// std::string if the string is nil or empty.
// assume #include <string>
std::string s = "";
if (([sInput != nil]) && (!([sInput isEqualTo:#""]))) {
std::string sTemp([sInput UTF8String]);
s = sTemp;
}
From there, I can use regex_replace like so:
// assume #include <regex>
std::string sResult = std::regex_replace(sSource,sRegExp,sReplaceWith);
Then, I can convert that std::string back into an NSString with:
NSString *sResponse2 = #(sResult.c_str());
If you're only using this C++ just for this function, then you may find it suitable to call this file extra.mm (class name Extra) and put this static class method in, and then add other static class methods when the situation arrives where it just makes sense to do it in C++ because it's less hassle in some cases. (There are cases where ObjC does something with less lines of code, and some cases where C++ does it with less lines of code.)
P.S. Still yet another way with this is to use a .mm file but make an Objective C wrapper around the use of std::string and std::regex_replace() (or regex_match()).
I'm working on writing my own Objective C wrapper around a minimal set of OpenAL functionality. One use case I'm trying to enable is transport controls after telling a sound to play like pause/stop/resume operations. I'm interested in trying to do this using what has been described to me as an "opaque type" or an id that conforms to a protocol in Objective C lingo. Does returning one of these make sense in this case, or would it be easier to just directly return an object and tie myself to that implementation?
And assuming the opaque type is the right approach, what would be a good name for the protocol? Right now I'm following this paradigm and calling the protocol OpenALPlaybackDelegate. I feel as if delegate doesn't really quite fit the model since the communication is happening the other way around.
An opaque type in this case is basically just a pointer that's used in Apple's C APIs in place of an object. Unlike a normal pointer to a struct full of stuff in C, the opacity in 'opaque types' comes from the fact that the header files don't expose the struct definition. The only way to deal with them is through the C functions that are exported. You see this in two places:
C APIs: Core Graphics, Core Audio, Core Foundation, Grand Central Dispatch. C has no objects. Apple has a bunch of types like CGFoobarRef that represent pointers to some sort of thing made with a function like CFFoobarMake();
Bridged APIs. Cocoa functionality is made available to C code through "the toll-free bridge", so you can generally get a handle on a say an instance of a Cocoa class in C world as an opaque type. Again, these generally end with Ref. All the Cocoa container classes, for instance, are available to C consumers through the Core Foundation toll-free bridge.
Relevant Apple documentation
If the consumers of your protocol are Objective-C libraries, which I'm going to assume they are, because that's the only way to use protocols, then no, it doesn't really make sense to expose access to any of your stuff as an pointer to a C struct filled with data and function pointers that are hidden from client code and exposed through a set of C functions.
Also, the reason to do this, for Apple, is encapsulation, data-hiding, etc. All it does is keep people from being able to muck about directly with the internal state of an object from C land, or write code that depends on it, because C lacks features like classes and ivars (well, Objective-C doesn't really have private ivars either but it at least has secret ones).
I would think writing an Objective-C wrapper around OpenAL, exactly what you would not want to do is return opaque types. You should return Objective-C objects that hold opaque type references with accessors/mutators that call the relevant functions on those references.