Xamarin.iOS linker and reflection issue - xamarin

In my Xamarin.iOS project I need to reduce the assembly size (Apple's requirement for AppStore applications), and I need to turn on linker, setting the linker behavior either to "Link Framework SDKs only" or "Link All".
When I've selected "Link Framework SDKs only" in Linker behavior I get the compilation error upon building the project:
Can't resolve the reference 'System.Void System.Data.SqlClient.SqlCommandBuilder::DeriveParameters(System.Data.SqlClient.SqlCommand)',
referenced from the method 'System.Void DevExpress.Xpo.DB.MSSqlConnectionProvider::CommandBuilderDeriveParameters(System.Data.IDbCommand)'
in 'System.Data.SqlClient, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
To fix this issue all answers I have found recommendation to turn "Link All" option in the Linker behavior option.
When I've selected "Link All", the project compiles okay, but at the runtime I get system exception on the IoC Container code (type AAA does not implement the interface BBB), because I use reflection, and linker with "Link All" options affects the code with the reflection. And as far as I know this linker option (Link All) is not recommended for the projects where reflection is being used.
What options do I have at this point?

Linker configuration
I suspect your best option is to look at define a configuration file to tell the Linker what must be kept. There is a good set of documentation on Microsofts documentation site.
There are some other options but may not strictly apply in this case or you may wish to use a combination.
Preserve Attribute
You can provide extra definitions to the linker to ensure the type, methods and/or fields are not eliminated from your application. In your own code the preferred way is to use the [Preserve] custom attribute, as discussed in the Linking on iOS and Linking on Android guides.
Linking for each platform is certainly a possibility however I suspect that you want to preserve things in your shared project which is why I think the config file will be right for you.
This approach gives you the ability to define at varying levels (e.g. assembly or class level to keep everything or down to individual properties/methods, etc.).
Actually reference the bits you need kept
I dislike this option very much but some people find it quick and easy to either prove you can keep parts of the code or just accept it is a solution.
You essentially create a class of actual references to the methods/properties that you want to be kept.
public class LinkerPleaseInclude
{
public void Include(MyType arg)
{
arg.MethodIDontWantRemoved();
}
}
Note I have sourced some details from this site

Related

Build Only for managed code

Is there any way to avoid building all the references of a dll in order to simulate a "Build Only" for managed dlls?
If you read the file %ProgramFiles(x86)%\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets, you'll find that building of referenced projects inside the target ResolveProjectReferencesis conditional on the property test '$(BuildPassReferences)' == 'true'.
If you set this property to false on MSBuild invocaton, references will not be rebuild:
msbuild ... /properties:BuildPassReferences=false,...
Note that this is not a supported feature, and that your compilation will likely genuinely fail if outputs of the referenced projects do not exist. Unlike C++ using include files to resolve external references, managed compilation needs existing reference DLLs.
So the answer is yes it is possible, not supported, and a clear step on the way into a trouble, unless the end you are trying to achieve is very specific and narrow.

Is there any class count limit in MFC project compiled with /CLR

With the risk to fall into too specific question...
Given a C++ MFC (mixed, not shaked) project compiled with /CLR, I have 200 classes already defined.
When I add a new empty class to this project, an error raises when I compile and execute in debug mode.
An unhandled exception of type 'System.IO.FileLoadException' occurred
in Unknown Module.
Additional information: Could not load file or assembly 'ProjectA,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. Could not find or load a type. (Exception from HRESULT:
0x80131522)
ProjectA is the name of the MFC project itself. There is no reference to any ProjectA assembly on project configuration, and there is no reference to another custom assembly.
This project only have references to some .NET Framework assemblies, in order to allow that some of custom defined classes in the project can use CLR classes.
Then, the question is...
Do you know whether there is any limitation of class number on a MFC C++ project?
EDIT:
As I say in comments, in release mode the compilation succeed without errors.
Also, I clean, build, clean, close Visual Studio, reboot computer... and the problem still appears.
If I keep in 200 classes, there is no error. When I go to 201, the error appears.
Currently I'm trying to reproduce in a new default MFC project, adding classes till arrive to 200, to confirm that there is a real limitation.
EDIT 2: ERROR FIXED
Great. #MSX and #frymode show me how avoid the error with his comments.
In the Visual Studio development environment (source / source):
Open the project's Property Pages dialog box.
Click the C/C++ folder.
Click the Code Generation property page.
Modify the Enable String Pooling (/GF) property.
Thank you guys!
The /GF hack is a known workaround for this problem. It is however not a correct one, you are putting a band-aid on a heavily bleeding wound. Pretty important that you heal the problem instead of putting a patch on it, this heavily affects the way your program runs at runtime as well.
The problem maker is the <Module> class, an internal class that the C++/CLI compiler generates. You can see it with ildasm.exe or a good decompiler. This class is required as a home for declarations in your program that are not class members, valid in native C++ but not supported by the CLR. Which demands that every variable or function declaration is a member of a class. The C++/CLI compiler solves it by moving such a declaration into the <Module> class.
There is however a limit on the number of members in a class, they are represented in the metadata of the .NET assembly with a metadata token. An index into other tables. The upper byte identifies the table number, the lower bytes are the index in the table.
You exceeded that limit. This is bad.
A problem with the /clr compile option is that it works too well. It is capable of compiling any C++03 compliant native C++ code to MSIL. Such code will be just-in-time compiled to machine code by the jitter, just like normal managed code. It is however not verifiable code and it doesn't act like managed code at all, you can blow up your program with pointer fumbles just as easily. And above all, it is not code that's optimized with the native C++ back-end. Only the jitter optimizer has a shot at improving that code, it cannot do nearly the quality job that the native C++ optimizer can do, given that it runs with a hard upper limit on how much time it can spend on doing that job.
Have a look-see with a decompiler to see what ended up in that <Module> class. That's going to be overwheliming at first, you know you've got a big one right now. You fix this problem by spending more time segregating the code into the managed parts and the native parts. Where the native code should be compiled without /clr in effect. It is a per-source file setting, you can even switch back-and-forth in a single source code file with #pragma managed. The simplest way to segregate is by keeping your native code in its own library or DLL.
This link shows that there's no limit to the number of types you can have in a namespace (not a project). Considering, that a namespace can be split across different assemblies, you could, at least in theory, have an unlimited number of types. However, this post affirms that the maximum number of classes in a .DLL
is 16777215. Probably, you'll run out of memory before you reach that number of classes :)
Just for information: there seems to be a limit to the number of fields per class, though.
P.S.:
Here's the solution to your problem taken from this link
Open the project's Property Pages dialog box.
Click the C/C++ folder.
Click the Code Generation property page.
Modify the Enable String Pooling property.

How should I get Xcode to link an iOS project that uses a C++ static library

Using Xcode, I've written a Cocoa Touch static library, mainly in C++. It exposes a C interface for the benefit of Objective-C client code.
I have a client iOS app that uses it, and everything works and runs as expected, except that I found I needed to include a minimal .cpp file in the client project to get the link to succeed. Otherwise I get C++-related unresolved symbols, e.g. operator new(unsigned long).
The above hack is easy and effective, and so I guess I'm not breaking any laws, but is there a proper way to eliminate my linker errors?
Should be just a matter of adding -lc++ to the linker flags in the project settings, I'd have thought.
Add it under "Other Linker Flags" under "Linking" section of the "Build Settings" tab on your project's settings.

Cmake add_library with boost source files introduces references to non-existant files

we're building a cross-platform utility which must have a small footprint. We've been pulling header files from boost as and when we need them but now we must link against some boost C++ thread code. The easiest immediate solution was to create our own custom library using CMake's "add_library" command to create a static library composed of some boost thread source files. These compile without any problems.
The difficulty arises when I try to link to this library from an executable. Visual Studio 2008 returns an error saying that it cannot link to "libboost_thread-vc90-mt-sgd-1_40.lib". What really puzzles me is that I've grepped through all the source code and CMake config files and I can't find any reference to this libboost library, leading me to think that this has been autogenerated in some way.
This works OK in Linux, can anyone point out why I'm experiencing these issues in Windows?
#Gearoid
You found the correct reason for your problem, but not the correct solution. The BOOST_AUTO_LINK_NOMANGLE is an internal, i.e. for library authors, definition to control the auto-linking. The user level definition is BOOST_ALL_NO_LIB which when defined disables the auto-linking feature for all Boost Libraries code you use. This is described in the user.hpp configuration header (see user.hpp near the bottom and the Boost Config documentation). You can also control this on a per library level as describe in that header.
Ok, well, it turns out that Boost uses this auto-link feature for Visual Studio which embeds references to a mangled (ie, platform-compiler-mult-threaded, etc) boost library name.
The header file which controls this is called "auto_link.hpp" which lives in the config directory of the boost include tree. There's a special preprocessor definition called "BOOST_AUTO_LINK_NOMANGLE" which toggles this behaviour.
Another triumph of mediocrity for Microsoft.

Strange VB6 build problems (related to nlog)

This I think is related to my use of the nlog C++ API (and my question on the nlog forum is here); the purpose of my asking this question here is to get a wider audience to my problem and perhaps to also get some more general ideas behind the VB6 IDE's failure to build in my particular scenario.
Briefly, the problem that I am having is that I am having trouble building VB6 components which reference unmanaged C++ components which have calls to nlog's C\C++ API (which is defined in NLogC.DLL). The build problems are not occurring during compile time, they are occurring when the binary is being built which suggests to me that it's some kind of linker type problem? Don't know enough about how VB6 binaries are produced to tell. The VB6 binary is produced, but it is corrupted and crashes shortly after it is invoked.
Has anyone had any similar experiences with VB6 (doesn't have to be related to nlog or C++)?
edit: Thanks for all the responses to this rather obscure problem. Still no headway unfortunately; my findings since I posted this:
'Tweaking' the compile options doesn't appear to help in this problem.
Adding a reference to the nlog-enabled C++ component from a 'blank' VB6 project doesn't crash it or cause weird build problems. So it isn't a 'native' VB6 issue, possibly an issue with the interaction between nlog and the various components and 3rd party libraries used by other referenced components?
As for C++ calling conventions: the nlog-enabled C++ component is - as far as I can see - compliant to these conventions and indeed works fine when referenced by VB6 as long as it is not making any nlog API calls. Not sure if the nlogc.DLL itself is VB6 compliant but I would have thought that that is immaterial since the API calls are being made from the C++ component; VB6 shouldn't know or care about what the C++ component is referencing (that's as far as my understanding on this goes...)
edit2: I should also note that the error message obtained during build is: "Errors during load. Please refer to "xxx" for details". When I bring up the log file, all that there is in there is: "Cannot load control xxx". Interestingly, all references to that particular control disappears from that particular project resulting in compile errors if I were to try to build again.
Got around the problem by using NLog's COM interface (NLog.ComInterop.DLL) from my unmanaged C++ code. Not as easy to do as the C\C++ API but at least it doesn't crash my VB6 components.
I would try tweaking some of the Compile options found in the Project, Properties menu, Compile panel to see if they yield any additional hints as to what is going wrong.
For example if you compile the executable to p-code rather than native code does it still crash on startup.
What error message do you get when you run your compiled binary?
I doubt the compiler/linker is the problem: project references in a VB6 project are not linked into the final executable. A project reference in VB6 is actually a reference to a COM type library (which may or may not be embedded in a .dll or other binary file type). Project references primarily serve two purposes:
The IDE extracts type information from the referenced type libraries which it then displays in the Object Browser (and in the Intellisense drop-down)
At compile-time, the compiler extracts the type information stored in the referenced libraries, including the CLSID of each class that you instantiate, and embeds this data into the executable. This allows your executable to create instances of classes contained in the libraries that you referenced.
Note that the compiled binary doesn't link to any code in the referenced libraries, and it doesn't even contain the filenames of the referenced libraries. The final executable only contains the CLSID's and other type information that it needs to instantiate COM objects at run-time.
It is much more likely that the issue is with NLog, or with how you are calling it from your code, rather than something gone awry in the VB6 compile process.
If you think it might be a linker problem, this should crash it the same way:
create a new standard project (of any kind)
add a new module and copy the "declare"-statements into it
compile
If it doesn't crash it is something else.
It would help an exact description of the error or a screenshot of what going on.
One thing to check is wherever NLogC.DLL or the C++ DLL you built have the correct calling convention defined. Basically you can't have the DLL function names mangled or use anything but the STDCALL calling convention. If the C++ DLL has not been created with those two things in mind then it will fail to work with VB6.
MSDN Article on Calling convention.
"Cannot load control xxx" errors can be caused by .oca files which were created from a different version of an .ocx than currently used. If that is the case, deleting the .oca files helps.

Resources