# Import a dll function in Mathematica?

**URL:** <https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509>\
**Category:** Questions\
**Tags:** compilation, external-interfaces, import-and-export\
**Created:** [May 10, 2017, 12:18pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509 "2017-05-10T12:18:31Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 10, 2017, 12:18pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/1 "2017-05-10T12:18:31Z")

</div>

I read that it’s possible import dll function in Mathematica.  
Now I ask you a question: suppose I have a c function

```
float * function(float * vertex, int * face)
{ 
       ....
       int size=getSize(vertex);
       float * r=new float[size];
       return r;    
}

```

Can I allocate memory inside dll and return data in Mathematica?  
How can I call a similar function from Mathematica? Is it possible to pass the result as an argument?  
Thanks in advance.

---

<div class="post-metadata">

**Author:** ![fkampas](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/fkampas/32/41217_2.png) [@fkampas](https://community.wolfram.com/u/fkampas)\
**Post date:** [May 10, 2017, 1:20pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/2 "2017-05-10T13:20:29Z")

</div>

> **[Calling COM & DLLs in the Wolfram Language —Wolfram Documentation](https://reference.wolfram.com/language/NETLink/guide/CallingCOMAndDLLs.html)**
>
> COM Objects, LoadCOMTypeLibrary \\\[LongDash\] load a type library for use in the Wolfram Language, CreateCOMObject, ReleaseCOMObject \\\[LongDash\] create or release COM objects, GetActiveCOMObject \\\[LongDash\] acquire an already-running COM object, Using...

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 10, 2017, 3:40pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/3 "2017-05-10T15:40:43Z")

</div>

If you write the C code yourself, the best way is using LibraryLink. Please see my old question about this:

- [https://mathematica.stackexchange.com/questions/8438/minimal-effort-method-for-integrating-c-functions-into-mathematica](https://mathematica.stackexchange.com/questions/8438/minimal-effort-method-for-integrating-c-functions-into-mathematica)

In particular, LibraryLink is the _only_ method that allows you to allocate memory yourself (indirectly), then pass this data to Mathematica _without copying_ and let Mathematica manage the memory from there on.

If you use the method linked by Frank, you will still be responsible for freeing that memory. (To be honest, I am not certain how this would work exactly, as it requires .NET expertise).

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 11, 2017, 7:31am UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/4 "2017-05-11T07:31:37Z")

</div>

Sorry where can I find some complete example with c code and mathematica code.  
I forget to say that my dll body function need to call some template c++ code.  
Now I ask you if NETLink or LibraryLink is again a solution.

```
float * function(float * vertex, int * face)
{ 
       // call template c++ code
       int size=getSize(vertex);
       float * r=new float[size];
       return r;    
}

```

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 11, 2017, 8:47am UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/5 "2017-05-11T08:47:41Z")

</div>

> Sorry where can I find some complete example with c code and Mathematica code.

I just gave you a link with several complete examples … did you look at it?

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 11, 2017, 4:09pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/6 "2017-05-11T16:09:28Z")

</div>

Ok I check your link and did some test with NetLink and after I executed the example for LibraryLink. In NetLink mmm sound like the output array size should be known because I allocate array before call the function. But if I need an function that return an array size where the size is determinated from the dll function itself it’s impraticable.

After I test LibraryLink. with one example and work right. But what’s I need is call a DLL that use some c++ code and template. If I tried add a simple class in MyLib.c compiler give me an error. I suppose its set a c compiler. It’s possibile use a c++ compiler in LibraryLink that support c++ template? I installed a mingw compiler c++ and set this as default.  
I use this command to set default compiler.

```
$CCompiler = {"Compiler" -> 
    CCompilerDriver`MinGWCompiler`MinGWCompiler, 
   "CompilerInstallation" -> "C:\\MinGW32-4.8.2"};

```

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 11, 2017, 4:38pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/7 "2017-05-11T16:38:20Z")

</div>

LibraryLink is a C interface. This means that it is straightforward to use it either from C or C++.

If you use `CreateLibrary` from within Mathematica, you should place the source code in a separate file that has a `.cpp` extension. Do not write the code in a Mathematica string. Put it in a separate file. Then everything will work out of the box.

If you use Windows, I strongly recommend you use the officially supported Microsoft compiler. You can download a compatible version [here](http://landinghub.visualstudio.com/visual-cpp-build-tools). Install the command line tools and the Windows SDK. No addition configuration is needed from within Mathematica.

Then start with the basic examples here:

- [List of LibraryLink examples](https://wolfram.discourse.group/t/1349/1)

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 12, 2017, 2:52pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/8 "2017-05-12T14:52:38Z")

</div>

Hello,  
thank you very much for help. I follow your guide and now I am able to compile some c++ code. I tried the CreateMatrix example. Now I would like ask you if it’s possibile return a list with different number of elements.  
I need an array vertex `{{1,2,3}, {5,4,6}, {3,4,5}, ...}` as input parameters and as output an array like this

```
{{1,2,3},{2,3,4,5,6,7,8},{3,3}}

```

It’s possibile return a similar array to Mathematica? Mathematica type it as “List”.

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 12, 2017, 3:09pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/9 "2017-05-12T15:09:14Z")

</div>

You will find the full LibraryLink user guide here:

- [Wolfram LibraryLink User Guide—Wolfram Documentation](https://reference.wolfram.com/language/LibraryLink/tutorial/Overview.html)

LibraryLink only has direct support for a few types, mostly full arrays. Ragged arrays (i.e. a general list of lists) is not _directly_ supported. You can use one of these two indirect ways:

1. Use MathLink from within a LibraryLink function. See the last two examples [here](https://wolfram.discourse.group/t/1349/1) , as well as the user guide. “MathLink” has recently been renamed WSTP for silly marketing reasons, which causes all sorts of inconveniences. You will notice that the user guide uses WS-prefixed functions, and the example I linked to uses ML-prefixed ones. The fact is that the WS-prefixed functions do not work in a straightforward way with LibraryLink (despite what the documentation says). Just use the ML-prefixed ones, and forget about “WSTP”. MathLink works just fine, even if it is “deprecated” according to the documentation.

2. Flatten your array into one long vector. Prepends the length of each sublist. Then prepend the number of sublists. Thus you would transform  
{{1,2}, {3,4,5}}

```
    (* almost the same as Internal`PartitionRagged *)
    partitionRagged[v_List, l_?VectorQ] := 
     MapThread[Take[v, {#1, #2}] &, 
      Module[{a = Accumulate[l]}, {a - l + 1, a}]]
    
    
    unpack[packed_] :=
     With[{len = Round@First[packed]},
      partitionRagged[
       1 + packed[[len + 2 ;; All]],
       Round[packed[[2 ;; len + 1]]]
       ]
      ]

```

---

<div class="post-metadata">

**Author:** ![fkampas](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/fkampas/32/41217_2.png) [@fkampas](https://community.wolfram.com/u/fkampas)\
**Post date:** [May 12, 2017, 3:49pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/10 "2017-05-12T15:49:00Z")

</div>

When I have used LibraryLink, I did all the transfers using MathLink, which is probably slower but much more powerful.

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 12, 2017, 4:08pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/11 "2017-05-12T16:08:21Z")

</div>

> When I have used LibraryLink, I did all the transfers using MathLink, which is probably slower but much more powerful.

That is very true. With MathLink it is possible to handle _any_ Mathematica expression. With plain LibraryLink, only a few.

But if you _only_ use LinkObject passing in LibraryLink, then is there any point to using LibraryLink at all? It also comes with big disadvantages compared to installable MathLink programs. If your code crashes, it will take down the whole kernel.

(I guess there may be a few reasons: you can use managed library expressions. But those don’t get a lot of use due to all the extra work they need. [LTemplate](https://github.com/szhorvat/LTemplate/) does take care of that problem though.)

---

<div class="post-metadata">

**Author:** ![fkampas](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/fkampas/32/41217_2.png) [@fkampas](https://community.wolfram.com/u/fkampas)\
**Post date:** [May 12, 2017, 4:20pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/12 "2017-05-12T16:20:34Z")

</div>

I was using LibraryLink and MathLink to transfer data to and from a C program which called Ipopt. I had to transfer the objective function, constraints, and their first and second derivatives as callbacks. ParametricIPOPT in version 11 rendered my code obsolete.

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 12, 2017, 4:30pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/13 "2017-05-12T16:30:24Z")

</div>

Thanks,  
I prefer pack solution.  
I tried in Mathematica the function unpack. Have you a pack function to send data from Mathematica to c++ side?  
If I need to send from Mathematica to c++ an array like it `{{1,2,3},{1,2},{5,6,7,8,9}}`. Now I am not able to write some pack function by could use the same way and unpack in c++ side.

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 12, 2017, 4:35pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/14 "2017-05-12T16:35:20Z")

</div>

Hey it’s interesting… can you give me some link with example? I would like learn also this method.

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 12, 2017, 4:55pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/15 "2017-05-12T16:55:35Z")

</div>

I do agree with Frank that unless you have special performance requirements, MathLink is a better choice here. It takes a bit of time to learn it, but once you have, you will find it much easier to use than all this error-prone packing/unpacking business. I used this packing technique (for integers, not reals) [because I did have special performance requirements](https://mathematica.stackexchange.com/a/95787/12). Due to the nature of the data I was working with, the data transfer itself took much longer than the computation.

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 12, 2017, 4:58pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/16 "2017-05-12T16:58:36Z")

</div>

[@Frank Kampas](http://community.wolfram.com/web/fkampas):

Have you seen the [“library callback functions”](https://reference.wolfram.com/language/LibraryLink/tutorial/InteractionWithMathematica.html#894022691)? They should offer much better performance than MathLink. They are only available since v10.0. I have not tried this functionality yet.

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 15, 2017, 9:36am UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/17 "2017-05-15T09:36:59Z")

</div>

I have special performance requirements too and large array to import in mathematica.  
Every time that I call createLibrary mathematica try to create a new dll and when it exist get a  
boring error CopyFile::filex: Cannot overwrite existing file C:\Users\ale\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\Windows\myLib.dll.

Do you know how solve this problem? To get a new version of dll for every modification I need to close mathematica  
delete dll files and execute again the command createLibrary this is very boring and time consuming.

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 15, 2017, 9:41am UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/18 "2017-05-15T09:41:12Z")

</div>

This may not work on all platforms, but it works on my Mac with M11.1.1:

Use `LibraryUnload` on the library before recompiling.

After recompiling, you will need to re-evaluate all the `LibraryFunctionLoad`s one by one.

My [LTemplate package](https://github.com/szhorvat/LTemplate/) makes this workflow slightly easier as you can just use a single `LoadTemplate` instead of multiple `LibraryFunctionLoad`s. The library still needs to be unloaded before recompiling with LTemplate. This is done using `UnloadTemplate`.

---

<div class="post-metadata">

**Author:** ![alessio211734](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@alessio211734](https://community.wolfram.com/u/alessio211734)\
**Post date:** [May 15, 2017, 3:39pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/19 "2017-05-15T15:39:19Z")

</div>

Thank you very much LibraryUnload resolve. Is it possible to make the dll part of the base Mathematica library?

---

<div class="post-metadata">

**Author:** ![szhorvat](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/szhorvat/32/3531_2.png) [@szhorvat](https://community.wolfram.com/u/szhorvat)\
**Post date:** [May 15, 2017, 4:05pm UTC](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509/20 "2017-05-15T16:05:24Z")

</div>

> Is it possible to make the dll part of the base mathematica library ?

I am not sure what you mean by this. Can you clarify?

[Next page](https://community.wolfram.com/t/import-a-dll-function-in-mathematica/10509.md?page=2)
